<?php
ini_set('display_errors',1);
error_reporting(E_ALL);

require_once __DIR__.'/../../../includes/auth.php';
requireLogin();
requirePermission('view_billing');

require_once __DIR__.'/../../../config/database.php';
require_once __DIR__.'/../../../includes/layout.php';

/* SAVE CUSTOMER */
if($_SERVER['REQUEST_METHOD'] === 'POST'){

    $name = trim($_POST['customer_name']);

    if($name === ''){
        $error = "Customer name is required.";
    } else {

        try {

            /* INSERT CUSTOMER */
$stmt = $pdo->prepare("
    INSERT INTO billing_customers 
    (customer_name, contact_person, contact_position, phone, office_phone, email, address, vat_number, registration_number)
    VALUES (?,?,?,?,?,?,?,?,?)
");

$stmt->execute([
    $_POST['customer_name'],
    $_POST['contact_person'],
    $_POST['contact_position'],
    $_POST['phone'],
    $_POST['office_phone'],
    $_POST['email'],
    $_POST['address'],
    $_POST['vat_number'],
    $_POST['registration_number']
]);

            $customerId = $pdo->lastInsertId();

            /* GENERATE CUSTOMER CODE */
            $customerCode = 'CUST-' . str_pad($customerId, 4, '0', STR_PAD_LEFT);

            /* UPDATE RECORD */
            $stmt = $pdo->prepare("
                UPDATE billing_customers
                SET customer_code = ?
                WHERE id = ?
            ");
            $stmt->execute([$customerCode, $customerId]);

            $success = "Customer created successfully.";

        } catch (Exception $e) {

            error_log($e->getMessage());
            $error = "Something went wrong while saving.";

        }

    }
}

?>

<div class="container">

<div class="page-header">
<h2>Add Customer</h2>
</div>

<?php if(isset($error)): ?>
<div style="background:#f8d7da;padding:10px;margin-bottom:10px;">
<?= $error ?>
</div>
<?php endif; ?>

<?php if(isset($success)): ?>
<div style="background:#d4edda;padding:10px;margin-bottom:10px;">
<?= $success ?>
</div>
<?php endif; ?>

<div class="stat-card">

<form method="POST">

<label>Customer Name</label>
<input type="text" name="customer_name" required>

<br><br>

<label>Contact Person</label>
<input type="text" name="contact_person">

<br><br>

<label>Contact Position</label>
<input type="text" name="contact_position">

<br><br>

<label>Mobile Phone</label>
<input type="text" name="phone">

<br><br>

<label>Office Phone</label>
<input type="text" name="office_phone">

<br><br>

<label>Email</label>
<input type="email" name="email">

<br><br>

<label>Address</label>
<textarea name="address"></textarea>

<br><br>

<label>VAT Number</label>
<input type="text" name="vat_number">

<br><br>

<label>Registration Number</label>
<input type="text" name="registration_number">

<br><br>

<button class="btn btn-primary">Save Customer</button>

</form>

</div>

</div>

<?php require_once __DIR__.'/../../../includes/layout_footer.php'; ?>