<?php
require_once "../config/auth.php";
require_once "../config/db.php";
require_once "../config/helpers.php";

require_once "../includes/header.php";
require_once "../includes/sidebar.php";
require_once "../includes/topbar.php";

$id = (int) ($_GET['id'] ?? 0);

// Fetch customer
$stmt = $conn->prepare("SELECT * FROM customers WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if($result->num_rows !== 1){
    die("Customer not found");
}

$customer = $result->fetch_assoc();
?>
<div class="main-content">
<div class="col-md-12">

<div class="topbar">
    <h5>Edit Customer</h5>
</div>

<div class="p-4">

    <form method="POST" action="../actions/update_customer.php" onsubmit="return validateForm()">

        <input type="hidden" name="id" value="<?php echo $customer['id']; ?>">

        <div class="mb-3">
            <label>Name *</label>
            <input type="text" name="name" id="name" class="form-control"
                   value="<?php echo e($customer['name']); ?>" required>
        </div>

        <div class="mb-3">
            <label>Email *</label>
            <input type="email" name="email" id="email" class="form-control"
                   value="<?php echo e($customer['email']); ?>" required>
        </div>

        <div class="mb-3">
            <label>Phone *</label>
            <input type="text" name="phone" id="phone" class="form-control"
                   value="<?php echo e($customer['phone']); ?>" maxlength="10" required>
            <small class="text-danger" id="phoneError"></small>
        </div>

        <div class="mb-3">
            <label>Address *</label>
            <textarea name="address" id="address" class="form-control" rows="3" required><?php echo e($customer['address']); ?></textarea>
        </div>

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

    </form>

</div>

</div>
</div>

<script>
function validateForm() {
    let phone = document.getElementById("phone").value.trim();
    let phoneError = document.getElementById("phoneError");

    if (!/^[0-9]+$/.test(phone)) {
        phoneError.innerText = "Only numbers allowed";
        return false;
    }

    if (phone.length !== 10) {
        phoneError.innerText = "Must be 10 digits";
        return false;
    }

    phoneError.innerText = "";
    return true;
}
</script>

<?php require_once "../includes/footer.php"; ?>
