<?php
session_start();
require_once '../config/database.php';
require_once '../config/helpers.php';
if (!can('clients','edit')) die('Access Denied');

$id = (int)$_GET['id'];
$client = $pdo->prepare("SELECT * FROM customers WHERE customer_id=?");
$client->execute([$id]);
$c = $client->fetch();
if (!$c) die('Not Found');

if ($_SERVER['REQUEST_METHOD']=='POST') {

    $imgName = $c['image'];
    if (!empty($_FILES['image']['name'])) {
        $imgName = time().'_'.$_FILES['image']['name'];
        move_uploaded_file($_FILES['image']['tmp_name'], "../uploads/clients/$imgName");
    }

    $stmt = $pdo->prepare("
        UPDATE customers SET
        name=?, phone=?, whatsapp=?, email=?,
        address=?, notes=?, image=?, status=?, updated_at=NOW()
        WHERE customer_id=?
    ");
    $stmt->execute([
        $_POST['name'], $_POST['phone'], $_POST['whatsapp'],
        $_POST['email'], $_POST['address'], $_POST['notes'],
        $imgName, $_POST['status'], $id
    ]);

    header("Location: clients.php");
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit Client</title>
<link rel="stylesheet" href="../assets/style.css">
</head>
<body>

<div class="card" style="max-width:500px;margin:40px auto">
<h2>Edit Client</h2>

<form method="post" enctype="multipart/form-data">
    <img id="preview"
         src="<?= $c['image']?'../uploads/clients/'.$c['image']:'assets/no-avatar.png' ?>"
         class="avatar-preview"><br><br>

    <input type="file" name="image" class="input" onchange="previewImage(event)">
    <input class="input" name="name" value="<?= $c['name'] ?>">
    <input class="input" name="phone" value="<?= $c['phone'] ?>">
    <input class="input" name="whatsapp" value="<?= $c['whatsapp'] ?>">
    <input class="input" name="email" value="<?= $c['email'] ?>">
    <input class="input" name="address" value="<?= $c['address'] ?>">
    <textarea class="input" name="notes"><?= $c['notes'] ?></textarea>

    <select class="input" name="status">
        <option value="1" <?= $c['status']?'selected':'' ?>>Active</option>
        <option value="0" <?= !$c['status']?'selected':'' ?>>Inactive</option>
    </select>

    <button class="btn btn-primary">Update</button>
    <a href="clients.php" class="btn btn-gray">Back</a>
</form>
</div>

<script>
function previewImage(e){
    document.getElementById('preview').src =
        URL.createObjectURL(e.target.files[0]);
}
</script>

</body>
</html>
