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

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

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

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

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

<div class="card" style="max-width:500px;margin:40px auto">
<h2>Add Client</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="Name" required>
    <input class="input" name="phone" placeholder="Phone">
    <input class="input" name="whatsapp" placeholder="WhatsApp">
    <input class="input" name="email" placeholder="Email">
    <input class="input" name="address" placeholder="Address">
    <textarea class="input" name="notes" placeholder="Notes"></textarea>

    <select class="input" name="status">
        <option value="1">Active</option>
        <option value="0">Inactive</option>
    </select>

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