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

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

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

function generateBookingRef(PDO $db): string {
    $year = date('Y');
    $count = $db->query("SELECT COUNT(*) as c FROM bookings WHERE YEAR(created_at) = $year")->fetch()['c'];
    return 'TC-' . $year . '-' . str_pad($count + 1, 4, '0', STR_PAD_LEFT);
}

switch ($action) {

    case 'list':
        $where = "1=1"; $params = [];
        if (!empty($_GET['status'])) { $where .= " AND b.status = ?"; $params[] = $_GET['status']; }
        $stmt = $db->prepare("
            SELECT b.*, c.name AS customer_name, c.phone AS customer_phone,
                   q.quote_ref,
                   COALESCE(SUM(p.amount), 0) AS paid_amount_actual,
                   u.name AS agent_name
            FROM bookings b
            LEFT JOIN customers c ON b.customer_id = c.id
            LEFT JOIN quotations q ON b.quotation_id = q.id
            LEFT JOIN payments p ON p.booking_id = b.id AND p.status = 'completed'
            LEFT JOIN users u ON b.created_by = u.id
            WHERE $where
            GROUP BY b.id
            ORDER BY b.created_at DESC
        ");
        $stmt->execute($params);
        jsonResponse(['success' => true, 'data' => $stmt->fetchAll()]);
        break;

    case 'get':
        $stmt = $db->prepare("
            SELECT b.*, c.name AS customer_name, c.phone AS customer_phone, c.email AS customer_email
            FROM bookings b
            LEFT JOIN customers c ON b.customer_id = c.id
            WHERE b.id = ?
        ");
        $stmt->execute([$id]);
        $b = $stmt->fetch();
        if (!$b) jsonResponse(['success' => false, 'error' => 'Not found'], 404);
        $payments = $db->prepare("SELECT p.*, u.name AS recorded_by_name FROM payments p LEFT JOIN users u ON p.recorded_by = u.id WHERE p.booking_id = ? ORDER BY p.created_at DESC");
        $payments->execute([$id]);
        $b['payments'] = $payments->fetchAll();
        jsonResponse(['success' => true, 'data' => $b]);
        break;

    case 'create':
        $input = getInput();
        $ref = generateBookingRef($db);
        $stmt = $db->prepare("
            INSERT INTO bookings (customer_id, quotation_id, booking_ref, destination, travel_date, return_date, num_passengers, total_amount, paid_amount, status, notes, created_by)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            intval($input['customer_id'] ?? 0) ?: null,
            intval($input['quotation_id'] ?? 0) ?: null,
            $ref,
            trim($input['destination'] ?? ''),
            $input['travel_date'] ?: null,
            $input['return_date'] ?: null,
            intval($input['num_passengers'] ?? 1),
            floatval($input['total_amount'] ?? 0),
            floatval($input['paid_amount'] ?? 0),
            $input['status'] ?? 'pending',
            trim($input['notes'] ?? ''),
            $currentUser['id']
        ]);
        $newId = $db->lastInsertId();
        logActivity($currentUser['id'], 'created', 'booking', $newId, "Booking: $ref");
        jsonResponse(['success' => true, 'id' => $newId, 'ref' => $ref, 'message' => 'Booking created']);
        break;

    case 'update':
        $input = getInput();
        $stmt = $db->prepare("
            UPDATE bookings SET customer_id=?, quotation_id=?, destination=?, travel_date=?, return_date=?, num_passengers=?, total_amount=?, status=?, notes=?
            WHERE id=?
        ");
        $stmt->execute([
            intval($input['customer_id'] ?? 0) ?: null,
            intval($input['quotation_id'] ?? 0) ?: null,
            trim($input['destination'] ?? ''),
            $input['travel_date'] ?: null,
            $input['return_date'] ?: null,
            intval($input['num_passengers'] ?? 1),
            floatval($input['total_amount'] ?? 0),
            $input['status'] ?? 'pending',
            trim($input['notes'] ?? ''),
            $id
        ]);
        logActivity($currentUser['id'], 'updated', 'booking', $id, "Updated booking ID: $id");
        jsonResponse(['success' => true, 'message' => 'Booking updated']);
        break;

    case 'update_status':
        $input = getInput();
        $allowed = ['pending','confirmed','cancelled','completed'];
        $status = $input['status'] ?? '';
        if (!in_array($status, $allowed)) jsonResponse(['success' => false, 'error' => 'Invalid status']);
        $db->prepare("UPDATE bookings SET status=? WHERE id=?")->execute([$status, $id]);
        jsonResponse(['success' => true, 'message' => 'Status updated']);
        break;

    case 'delete':
        $db->prepare("DELETE FROM bookings WHERE id=?")->execute([$id]);
        jsonResponse(['success' => true, 'message' => 'Booking deleted']);
        break;

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