<?php
require_once __DIR__ . '/config.php';

$currentUser = requireAuth();
$db = getDB();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'list';
$id = intval($_GET['id'] ?? 0);

header('Content-Type: application/json');

switch ($action) {

    case 'list':
        $search = $_GET['search'] ?? '';
        $params = [];
        $where = "1=1";
        if ($search) {
            $where .= " AND (c.name LIKE ? OR c.phone LIKE ? OR c.email LIKE ? OR c.passport_no LIKE ?)";
            $s = "%$search%";
            $params = [$s, $s, $s, $s];
        }
        $stmt = $db->prepare("
            SELECT c.*, 
                   COUNT(DISTINCT b.id) as booking_count,
                   SUM(CASE WHEN b.status='confirmed' THEN b.total_amount ELSE 0 END) as total_spent
            FROM customers c
            LEFT JOIN bookings b ON b.customer_id = c.id
            WHERE $where
            GROUP BY c.id
            ORDER BY c.created_at DESC
        ");
        $stmt->execute($params);
        jsonResponse(['success' => true, 'data' => $stmt->fetchAll()]);
        break;

    case 'get':
        $stmt = $db->prepare("SELECT c.*, l.destination AS lead_destination FROM customers c LEFT JOIN leads l ON c.lead_id = l.id WHERE c.id = ?");
        $stmt->execute([$id]);
        $customer = $stmt->fetch();
        if (!$customer) jsonResponse(['success' => false, 'error' => 'Customer not found'], 404);

        $bookings = $db->prepare("SELECT b.*, SUM(p.amount) as paid FROM bookings b LEFT JOIN payments p ON p.booking_id = b.id WHERE b.customer_id = ? GROUP BY b.id ORDER BY b.travel_date DESC");
        $bookings->execute([$id]);
        $customer['bookings'] = $bookings->fetchAll();
        jsonResponse(['success' => true, 'data' => $customer]);
        break;

    case 'create':
        $input = getInput();
        $stmt = $db->prepare("
            INSERT INTO customers (lead_id, name, phone, email, dob, nationality, passport_no, passport_expiry, address, emergency_contact, notes)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            intval($input['lead_id'] ?? 0) ?: null,
            trim($input['name'] ?? ''),
            trim($input['phone'] ?? ''),
            trim($input['email'] ?? ''),
            $input['dob'] ?: null,
            trim($input['nationality'] ?? ''),
            trim($input['passport_no'] ?? ''),
            $input['passport_expiry'] ?: null,
            trim($input['address'] ?? ''),
            trim($input['emergency_contact'] ?? ''),
            trim($input['notes'] ?? ''),
        ]);
        $newId = $db->lastInsertId();
        logActivity($currentUser['id'], 'created', 'customer', $newId, "Customer: " . ($input['name'] ?? ''));
        jsonResponse(['success' => true, 'id' => $newId, 'message' => 'Customer created']);
        break;

    case 'update':
        $input = getInput();
        $stmt = $db->prepare("
            UPDATE customers SET name=?, phone=?, email=?, dob=?, nationality=?, passport_no=?, passport_expiry=?, address=?, emergency_contact=?, notes=?
            WHERE id=?
        ");
        $stmt->execute([
            trim($input['name'] ?? ''),
            trim($input['phone'] ?? ''),
            trim($input['email'] ?? ''),
            $input['dob'] ?: null,
            trim($input['nationality'] ?? ''),
            trim($input['passport_no'] ?? ''),
            $input['passport_expiry'] ?: null,
            trim($input['address'] ?? ''),
            trim($input['emergency_contact'] ?? ''),
            trim($input['notes'] ?? ''),
            $id
        ]);
        logActivity($currentUser['id'], 'updated', 'customer', $id, "Updated customer ID: $id");
        jsonResponse(['success' => true, 'message' => 'Customer updated']);
        break;

    case 'delete':
        $db->prepare("DELETE FROM customers WHERE id=?")->execute([$id]);
        logActivity($currentUser['id'], 'deleted', 'customer', $id, "Deleted customer ID: $id");
        jsonResponse(['success' => true, 'message' => 'Customer deleted']);
        break;

    default:
        jsonResponse(['success' => false, 'error' => 'Unknown action'], 400);
}
