<?php
require 'auth_check.php';
require '../config/db.php';

$msg = "";
$msgClass = "";

// 1. ADD / UPDATE VENDOR
if (isset($_POST['save_vendor'])) {
    $name = trim($_POST['name']);
    $phone = trim($_POST['whatsapp_number']);
    $email = trim($_POST['email']);
    $notes = trim($_POST['notes']);
    $active = isset($_POST['is_active']) ? 1 : 0;

    if (!empty($_POST['vendor_id'])) {
        // UPDATE
        $stmt = $pdo->prepare("UPDATE vendors SET name=?, whatsapp_number=?, email=?, notes=?, is_active=? WHERE id=?");
        $stmt->execute([$name, $phone, $email, $notes, $active, $_POST['vendor_id']]);
        $msg = "Vendor updated!"; $msgClass = "success";
    } else {
        // INSERT
        $stmt = $pdo->prepare("INSERT INTO vendors (name, whatsapp_number, email, notes, is_active) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([$name, $phone, $email, $notes, $active]);
        $msg = "Vendor added!"; $msgClass = "success";
    }
}

// 2. DELETE VENDOR
if (isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM vendors WHERE id=?")->execute([$_GET['delete']]);
    header("Location: vendors.php?msg=deleted"); exit();
}

// 3. FETCH DATA
$edit_vendor = null;
if (isset($_GET['edit'])) {
    $edit_vendor = $pdo->query("SELECT * FROM vendors WHERE id=" . $_GET['edit'])->fetch();
}
$vendors = $pdo->query("SELECT * FROM vendors ORDER BY id DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Vendors</title>
    <link rel="stylesheet" href="admin_style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .msg-box { padding:10px; border-radius:5px; margin-bottom:20px; text-align:center; }
        .success { background:#d4edda; color:#155724; } 
        .error { background:#f8d7da; color:#721c24; }
        
        .form-card { background:white; padding:20px; border-radius:8px; margin-bottom:30px; box-shadow:0 2px 5px rgba(0,0,0,0.05); border-top:4px solid #f39c12; }
        .input-row { display:flex; gap:15px; margin-bottom:15px; }
        .form-control { width:100%; padding:10px; border:1px solid #ddd; border-radius:4px; }
        .btn-save { background:#f39c12; color:white; border:none; padding:10px 20px; cursor:pointer; border-radius:4px; font-weight:bold; }
        
        table { width:100%; background:white; border-collapse:collapse; }
        th { background:#eee; padding:10px; text-align:left; }
        td { padding:10px; border-bottom:1px solid #eee; }
        .wa-link { color:#25D366; font-weight:bold; text-decoration:none; }
    </style>
</head>
<body>
    <div class="sidebar"><?php include 'sidebar.php'; ?></div>

    <div class="content">
        <h1>Vendor Management</h1>
        <?php if($msg): ?><div class="msg-box <?php echo $msgClass; ?>"><?php echo $msg; ?></div><?php endif; ?>

        <!-- FORM -->
        <div class="form-card">
            <h3><?php echo $edit_vendor ? "Edit Vendor" : "Add New Vendor"; ?></h3>
            <form method="POST">
                <input type="hidden" name="vendor_id" value="<?php echo $edit_vendor['id'] ?? ''; ?>">
                
                <div class="input-row">
                    <input type="text" name="name" class="form-control" placeholder="Vendor Name (e.g. Ali Tech)" required value="<?php echo $edit_vendor['name'] ?? ''; ?>">
                    <input type="text" name="whatsapp_number" class="form-control" placeholder="WhatsApp (e.g. 919876543210)" required value="<?php echo $edit_vendor['whatsapp_number'] ?? ''; ?>">
                </div>
                <div class="input-row">
                    <input type="email" name="email" class="form-control" placeholder="Email (Optional)" value="<?php echo $edit_vendor['email'] ?? ''; ?>">
                    <input type="text" name="notes" class="form-control" placeholder="Notes (e.g. Deals in Adobe)" value="<?php echo $edit_vendor['notes'] ?? ''; ?>">
                </div>
                <div style="margin-bottom:15px;">
                    <label><input type="checkbox" name="is_active" <?php echo (!$edit_vendor || $edit_vendor['is_active']) ? 'checked' : ''; ?>> Active Vendor</label>
                </div>
                <button type="submit" name="save_vendor" class="btn-save">Save Vendor</button>
            </form>
        </div>

        <!-- LIST -->
        <h3>Vendor List</h3>
        <table>
            <thead><tr><th>Name</th><th>WhatsApp</th><th>Notes</th><th>Status</th><th>Action</th></tr></thead>
            <tbody>
                <?php foreach($vendors as $v): ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($v['name']); ?></strong></td>
                    <td><a href="https://wa.me/<?php echo $v['whatsapp_number']; ?>" target="_blank" class="wa-link"><i class="fab fa-whatsapp"></i> <?php echo $v['whatsapp_number']; ?></a></td>
                    <td><?php echo htmlspecialchars($v['notes']); ?></td>
                    <td><?php echo $v['is_active'] ? '<span style="color:green">Active</span>' : '<span style="color:red">Inactive</span>'; ?></td>
                    <td>
                        <a href="vendors.php?edit=<?php echo $v['id']; ?>" style="color:blue;">Edit</a> | 
                        <a href="vendors.php?delete=<?php echo $v['id']; ?>" style="color:red;" onclick="return confirm('Delete?')">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</body>
</html>