<?php
session_start();
require_once '../config/database.php';
require_once '../config/helpers.php';

if (!can('agents','edit')) die('Access Denied');

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

$stmt = $pdo->prepare("SELECT * FROM agents WHERE agent_id=?");
$stmt->execute([$id]);
$a = $stmt->fetch();
if (!$a) die('Not Found');

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

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

    $stmt = $pdo->prepare("
        UPDATE agents SET
        name=?, country=?, phone=?, email=?, whatsapp=?,
        notes=?, image=?, status=?, updated_at=NOW()
        WHERE agent_id=?
    ");
    $stmt->execute([
        $_POST['name'], $_POST['country'], $_POST['phone'],
        $_POST['email'], $_POST['whatsapp'], $_POST['notes'],
        $img, $_POST['status'], $id
    ]);

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

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

<form method="post" enctype="multipart/form-data">

    <img id="preview"
         src="<?= $a['image'] ? '../uploads/agents/'.$a['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="<?= htmlspecialchars($a['name']) ?>">
    <input class="input" name="country" value="<?= htmlspecialchars($a['country']) ?>">
    <input class="input" name="phone" value="<?= htmlspecialchars($a['phone']) ?>">
    <input class="input" name="whatsapp" value="<?= htmlspecialchars($a['whatsapp']) ?>">
    <input class="input" name="email" value="<?= htmlspecialchars($a['email']) ?>">
    <textarea class="input" name="notes"><?= htmlspecialchars($a['notes']) ?></textarea>

    <select class="input" name="status">
        <option value="active" <?= $a['status']=='active'?'selected':'' ?>>Active</option>
        <option value="inactive" <?= $a['status']=='inactive'?'selected':'' ?>>Inactive</option>
    </select>

    <button class="btn btn-primary">Update</button>
    <a href="agents.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>
