<?php
require 'db.php';

// 1. Handle Bulk Update
if (isset($_POST['bulk_action']) && $_POST['bulk_action'] === 'update_location') {
    $ids = $_POST['customer_ids'] ?? [];
    $new_location_id = !empty($_POST['bulk_location_id']) ? $_POST['bulk_location_id'] : null;
    
    if (!empty($ids)) {
        // Create placeholders for the IN clause (?,?,?)
        $placeholders = str_repeat('?,', count($ids) - 1) . '?';
        
        // Merge the location ID with the list of customer IDs for the params array
        $params = array_merge([$new_location_id], $ids);
        
        $sql = "UPDATE customers SET location_id = ? WHERE id IN ($placeholders)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
    }
    header("Location: customers.php");
    exit;
}

// 2. Handle Add / Update Single
if (isset($_POST['action']) && $_POST['action'] === 'save_single') {
    $name = trim($_POST['name']);
    $location_id = !empty($_POST['location_id']) ? $_POST['location_id'] : null;
    $calix_position    = trim($_POST['calix_position'] ?? '');
    $splitter_position = trim($_POST['splitter_position'] ?? '');
    $phone1            = trim($_POST['phone1'] ?? '');
    $phone2            = trim($_POST['phone2'] ?? '');

    if (!empty($_POST['id'])) {
        $stmt = $pdo->prepare("UPDATE customers SET name = ?, location_id = ?, calix_position = ?, splitter_position = ?, phone1 = ?, phone2 = ? WHERE id = ?");
        $stmt->execute([$name, $location_id, $calix_position, $splitter_position, $phone1, $phone2, $_POST['id']]);
    } else {
        // Check for duplicate name before inserting
        $stmtCheck = $pdo->prepare("SELECT id FROM customers WHERE name = ?");
        $stmtCheck->execute([$name]);
        if (!$stmtCheck->fetch()) {
            $stmt = $pdo->prepare("INSERT INTO customers (name, location_id, calix_position, splitter_position, phone1, phone2) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $location_id, $calix_position, $splitter_position, $phone1, $phone2]);
        }
    }
    header("Location: customers.php");
    exit;
}

// 3. Handle Delete Single
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
    $stmt = $pdo->prepare("DELETE FROM customers WHERE id = ?");
    $stmt->execute([$_POST['delete']]);
    header("Location: customers.php");
    exit;
}

// Fetch Data
$locations = $pdo->query("SELECT * FROM locations ORDER BY name ASC")->fetchAll();
$customers = $pdo->query("
    SELECT c.*, l.name as loc_name 
    FROM customers c 
    LEFT JOIN locations l ON c.location_id = l.id 
    ORDER BY c.name ASC
")->fetchAll();

$edit_customer = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $edit_customer = $stmt->fetch();
}
?>
<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Customers</title>
    <link rel="stylesheet" href="/assets/css/tailwind.min.css">
    
    <script>
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
            document.documentElement.classList.add('dark');
            document.documentElement.style.backgroundColor = '#111827';
        } else {
            document.documentElement.classList.remove('dark');
            document.documentElement.style.backgroundColor = '#f3f4f6';
        }
    </script>
    <link href="/assets/css/font-awesome.min.css" rel="stylesheet">
    <style>
        .animate-bounce-in { animation: bounceIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
        @keyframes bounceIn {
            0% { transform: translate(-50%, 100%); opacity: 0; }
            100% { transform: translate(-50%, 0); opacity: 1; }
        }
    </style>
</head>
<body class="bg-gray-100 dark:bg-gray-900 text-gray-800 dark:text-gray-200 h-full flex overflow-hidden text-sm">

    <?php include 'sidebar.php'; ?>

    <main class="flex-1 flex flex-col h-full overflow-hidden relative">
        <header class="h-14 bg-white dark:bg-gray-800 shadow flex items-center px-6 justify-between shrink-0">
            <div class="flex items-center">
                <button class="open-sidebar-btn md:hidden mr-3 text-gray-500 hover:text-blue-600 transition">
                    <i class="fas fa-bars text-xl"></i>
                </button>
                <h2 class="font-bold text-lg text-gray-700 dark:text-gray-200">Manage Customers</h2>
            </div>
        </header>

        <div class="flex-1 overflow-auto p-4 md:p-6 flex flex-col md:flex-row gap-6 items-start">
            
            <div class="w-full md:w-1/3 bg-white dark:bg-gray-800 p-5 rounded shadow border border-gray-200 dark:border-gray-700 shrink-0 md:sticky md:top-0">
                <h3 class="font-bold uppercase tracking-wider text-xs text-gray-500 mb-4"><?= $edit_customer ? 'Edit Customer' : 'Add New Customer' ?></h3>
                <form method="POST" class="flex flex-col gap-4">
                    <input type="hidden" name="action" value="save_single">
                    <input type="hidden" name="id" value="<?= $edit_customer['id'] ?? '' ?>">
                    <div>
                        <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Customer Name</label>
                        <input type="text" name="name" value="<?= htmlspecialchars($edit_customer['name'] ?? '') ?>" required class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 focus:outline-none focus:border-blue-500">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Default Location</label>
                        <select name="location_id" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-2 focus:outline-none focus:border-blue-500">
                            <option value="">-- No Specific Location --</option>
                            <?php foreach($locations as $l): ?>
                                <option value="<?= $l['id'] ?>" <?= (($edit_customer['location_id'] ?? '') == $l['id']) ? 'selected' : '' ?>><?= htmlspecialchars($l['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="border-t border-gray-200 dark:border-gray-700 pt-3 mt-1">
                        <h4 class="font-bold text-blue-600 dark:text-blue-400 uppercase text-[10px] tracking-wide mb-3">Plant Information</h4>
                        <div class="flex flex-col gap-3">
                            <div>
                                <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Calix Position</label>
                                <input type="text" name="calix_position" value="<?= htmlspecialchars($edit_customer['calix_position'] ?? '') ?>" placeholder="e.g. 1-2-1-468" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 focus:outline-none focus:border-blue-500 font-mono text-xs">
                            </div>
                            <div>
                                <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Splitter Position</label>
                                <input type="text" name="splitter_position" value="<?= htmlspecialchars($edit_customer['splitter_position'] ?? '') ?>" placeholder="e.g. 1-2-1-6" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 focus:outline-none focus:border-blue-500 font-mono text-xs">
                            </div>
                        </div>
                    </div>

                    <div class="border-t border-gray-200 dark:border-gray-700 pt-3 mt-1">
                        <h4 class="font-bold text-blue-600 dark:text-blue-400 uppercase text-[10px] tracking-wide mb-3">Contact</h4>
                        <div class="flex flex-col gap-3">
                            <div>
                                <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Phone 1</label>
                                <input type="text" name="phone1" value="<?= htmlspecialchars($edit_customer['phone1'] ?? '') ?>" placeholder="e.g. 308-555-1234" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 focus:outline-none focus:border-blue-500">
                            </div>
                            <div>
                                <label class="block text-[10px] font-bold text-gray-400 uppercase mb-1">Phone 2</label>
                                <input type="text" name="phone2" value="<?= htmlspecialchars($edit_customer['phone2'] ?? '') ?>" placeholder="e.g. 308-555-5678" class="w-full h-[34px] bg-gray-50 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded px-3 focus:outline-none focus:border-blue-500">
                            </div>
                        </div>
                    </div>

                    <div class="flex gap-2 mt-2 pt-2">
                        <?php if($edit_customer): ?>
                            <a href="customers.php" class="bg-gray-500 text-white px-4 py-2 rounded text-xs font-bold uppercase w-1/3 text-center flex items-center justify-center">Cancel</a>
                        <?php endif; ?>
                        <button type="submit" class="bg-blue-600 hover:bg-blue-500 text-white px-4 py-2 rounded shadow font-bold uppercase text-xs transition flex-1">Save Customer</button>
                    </div>
                </form>
            </div>

            <form method="POST" id="bulkForm" class="w-full md:w-2/3 bg-white dark:bg-gray-800 rounded shadow border border-gray-200 dark:border-gray-700 flex flex-col flex-1 min-h-[400px] overflow-hidden relative">
                <input type="hidden" name="bulk_action" value="update_location">
                
                <div class="overflow-x-auto overflow-y-auto flex-1 w-full">
                    <table class="w-full text-left border-collapse min-w-[600px]">
                        <thead>
                            <tr class="bg-gray-50 dark:bg-gray-700/50 text-[10px] uppercase text-gray-500 dark:text-gray-400 font-bold border-b dark:border-gray-700 tracking-wider sticky top-0 z-10 backdrop-blur-sm">
                                <th class="px-4 py-3 w-10 text-center">
                                    <input type="checkbox" onclick="toggleAll(this)" class="rounded border-gray-300 text-blue-600 focus:ring-blue-500 cursor-pointer">
                                </th>
                                <th class="px-4 py-3 whitespace-nowrap">Customer Name</th>
                                <th class="px-4 py-3 w-32 whitespace-nowrap">Location</th>
                                <th class="px-4 py-3 w-40 whitespace-nowrap">Calix Pos</th>
                                <th class="px-4 py-3 w-32 whitespace-nowrap">Splitter Pos</th>
                                <th class="px-4 py-3 w-36 whitespace-nowrap">Phone</th>
                                <th class="px-4 py-3 w-20 text-right whitespace-nowrap">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-700 text-xs">
                            <?php foreach($customers as $c): ?>
                            <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors group">
                                <td class="px-4 py-2 text-center">
                                    <input type="checkbox" name="customer_ids[]" value="<?= $c['id'] ?>" onchange="updateCount()" class="cust-check rounded border-gray-300 text-blue-600 focus:ring-blue-500 cursor-pointer">
                                </td>
                                <td class="px-4 py-2 font-bold text-gray-700 dark:text-gray-200 whitespace-nowrap"><?= htmlspecialchars($c['name']) ?></td>
                                <td class="px-4 py-2 whitespace-nowrap">
                                    <?php if($c['loc_name']): ?>
                                        <span class="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300">
                                            <?= htmlspecialchars($c['loc_name']) ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-gray-400 italic">Not Set</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-4 py-2 font-mono text-[11px] text-gray-500 dark:text-gray-400 whitespace-nowrap"><?= htmlspecialchars($c['calix_position'] ?: '-') ?></td>
                                <td class="px-4 py-2 font-mono text-[11px] text-gray-500 dark:text-gray-400 whitespace-nowrap"><?= htmlspecialchars($c['splitter_position'] ?: '-') ?></td>
                                <td class="px-4 py-2 text-[11px] text-gray-500 dark:text-gray-400 whitespace-nowrap">
                                    <?php if ($c['phone1'] || $c['phone2']): ?>
                                        <?php if ($c['phone1']): ?><div><?= htmlspecialchars($c['phone1']) ?></div><?php endif; ?>
                                        <?php if ($c['phone2']): ?><div class="text-gray-400"><?= htmlspecialchars($c['phone2']) ?></div><?php endif; ?>
                                    <?php else: ?>
                                        <span class="text-gray-400 italic">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-4 py-2 text-right">
                                    <div class="flex justify-end gap-3 md:opacity-0 md:group-hover:opacity-100 transition-opacity">
                                        <a href="customers.php?edit=<?= $c['id'] ?>" class="text-gray-400 hover:text-blue-500 p-2 md:p-0"><i class="fas fa-pen"></i></a>
                                        <form method="POST" class="inline" onsubmit="return confirm('Delete customer? This might orphan historical jobs.');">
                                            <input type="hidden" name="delete" value="<?= $c['id'] ?>">
                                            <button type="submit" class="text-gray-400 hover:text-red-500 p-2 md:p-0"><i class="fas fa-trash"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div id="actionBar" class="hidden absolute bottom-4 left-1/2 transform -translate-x-1/2 bg-slate-800 text-white px-3 py-2 md:px-4 md:py-2 rounded-xl md:rounded-full shadow-2xl z-50 items-center justify-center gap-2 md:gap-3 animate-bounce-in border border-slate-600 w-[90%] md:w-auto flex-wrap md:flex-nowrap">
                    <span class="text-[10px] font-bold uppercase whitespace-nowrap"><span id="countSelected">0</span> Selected</span>
                    <div class="hidden md:block h-4 w-px bg-slate-600"></div>
                    <select name="bulk_location_id" class="bg-slate-700 border-none text-xs rounded px-2 py-1 text-white focus:ring-0 cursor-pointer w-full md:w-auto">
                        <option value="">-- Assign Location --</option>
                        <?php foreach($locations as $l): ?>
                            <option value="<?= $l['id'] ?>"><?= htmlspecialchars($l['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit" class="bg-blue-600 hover:bg-blue-500 text-white px-3 py-1 rounded md:rounded-full text-[10px] font-bold uppercase transition w-full md:w-auto">
                        Update
                    </button>
                </div>
            </form>

        </div>
    </main>

    <script>
        function toggleAll(source) {
            document.querySelectorAll('.cust-check').forEach(cb => cb.checked = source.checked);
            updateCount();
        }

        function updateCount() {
            const count = document.querySelectorAll('.cust-check:checked').length;
            document.getElementById('countSelected').innerText = count;
            const bar = document.getElementById('actionBar');
            
            if (count > 0) {
                bar.classList.remove('hidden');
                bar.classList.add('flex');
            } else {
                bar.classList.add('hidden');
                bar.classList.remove('flex');
            }
        }

    </script>
</body>
</html>