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

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

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

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

    $stmt = $pdo->prepare("
        INSERT INTO agents
        (name, country, phone, email, whatsapp, notes, image, status, created_at)
        VALUES (?,?,?,?,?,?,?,?,NOW())
    ");
    $stmt->execute([
        $_POST['name'], $_POST['country'], $_POST['phone'],
        $_POST['email'], $_POST['whatsapp'], $_POST['notes'],
        $img, $_POST['status']
    ]);

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

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

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

    <img id="preview" src="../assets/no-avatar.png" class="avatar-preview"><br><br>
    <input type="file" name="image" class="input" accept="image/*"
           onchange="previewImage(event)">

    <input class="input" name="name" placeholder="Agent Name" required>
    <input class="input" name="country" placeholder="Country">
    <input class="input" name="phone" placeholder="Phone">
    <input class="input" name="whatsapp" placeholder="WhatsApp">
    <input class="input" name="email" placeholder="Email">
    <textarea class="input" name="notes" placeholder="Notes"></textarea>

    <select class="input" name="status">
        <option value="active">Active</option>
        <option value="inactive">Inactive</option>
    </select>

    <button class="btn btn-success">Save</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>
