<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$id = intval($_GET['id'] ?? 0);
if (!$id) {
    echo "<script>alert('Invalid customer');window.location='customers.php';</script>";
    exit;
}

// Fetch customer
$c = $conn->query("SELECT * FROM customers WHERE id = $id")->fetch_assoc();

if (!$c) {
    echo "<script>alert('Customer not found');window.location='customers.php';</script>";
    exit;
}

// Update
if (isset($_POST['update_customer'])) {
    $name = $conn->real_escape_string($_POST['name']);
    $phone = $conn->real_escape_string($_POST['phone']);
    $email = $conn->real_escape_string($_POST['email']);
    $address = $conn->real_escape_string($_POST['address']);

    $conn->query("UPDATE customers SET 
            name='$name', 
            phone='$phone', 
            email='$email', 
            address='$address'
        WHERE id=$id");

    echo "<script>alert('Customer updated');window.location='customers.php';</script>";
    exit;
}
?>

<div class="container mt-4">
      <!-- ================= WELCOME MESSAGE ================= -->
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>
    <h3>Edit Customer</h3>
    <hr>

    <form method="POST" class="row g-3">
        <div class="col-md-6">
            <label>Name</label>
            <input type="text" name="name" value="<?= $c['name'] ?>" class="form-control" required>
        </div>

        <div class="col-md-6">
            <label>Phone</label>
            <input type="text" name="phone" value="<?= $c['phone'] ?>" class="form-control">
        </div>

        <div class="col-md-6">
            <label>Email</label>
            <input type="email" name="email" value="<?= $c['email'] ?>" class="form-control">
        </div>

        <div class="col-md-6">
            <label>Address</label>
            <input type="text" name="address" value="<?= $c['address'] ?>" class="form-control">
        </div>

        <div class="col-md-12 mt-3">
            <button class="btn btn-success" name="update_customer"><i class="fa fa-save"></i> Update</button>
            <a href="customers.php" class="btn btn-danger"><i class="fa fa-arrow-left"></i> Back</a>
        </div>
    </form>
</div>

<?php include 'includes/footer.php'; ?>
