<?php
session_start();
require_once '../config/database.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

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

if (!isLoggedIn()) {
    jsonResponse(false, 'Unauthorized');
}

requireAdmin();

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'save_booking':
        saveBooking();
        break;
    
    case 'update_booking':
        updateBooking();
        break;
    
    case 'delete_booking':
        deleteBooking();
        break;
    
    case 'get_booking_list':
        getBookingList();
        break;
    
    case 'get_booking':
        getBooking();
        break;
    
    default:
        jsonResponse(false, 'Invalid action');
}

function saveBooking() {
    try {
        // Get data
        $nama_organisasi = clean($_POST['nama_organisasi'] ?? '');
        $nama_pic = clean($_POST['nama_pic'] ?? '');
        $no_telepon = clean($_POST['no_telepon'] ?? '');
        $tanggal_kedatangan = clean($_POST['tanggal_kedatangan'] ?? '');
        $items = json_decode($_POST['items'] ?? '[]', true);
        $subtotal = floatval($_POST['subtotal'] ?? 0);
        $diskon = floatval($_POST['diskon'] ?? 0);
        $total = floatval($_POST['total'] ?? 0);
        $dp = floatval($_POST['dp'] ?? 0);
        $sisa = floatval($_POST['sisa'] ?? 0);
        $user_id = $_SESSION['user_id'];
        
        // Validasi
        if (empty($nama_organisasi) || empty($nama_pic) || empty($no_telepon) || empty($tanggal_kedatangan)) {
            jsonResponse(false, 'Data organisasi tidak lengkap');
        }
        
        if (empty($items) || $subtotal <= 0) {
            jsonResponse(false, 'Minimal harus ada 1 item');
        }
        
        // Validasi tanggal
        if (strtotime($tanggal_kedatangan) < strtotime(date('Y-m-d'))) {
            jsonResponse(false, 'Tanggal kedatangan tidak boleh kurang dari hari ini');
        }
        
        // Validasi diskon
        if ($diskon > $subtotal) {
            jsonResponse(false, 'Diskon tidak boleh lebih dari subtotal');
        }
        
        // Validasi DP
        if ($dp > $total) {
            jsonResponse(false, 'DP tidak boleh lebih dari total');
        }
        
        $conn = getConnection();
        $conn->begin_transaction();
        
        try {
            // Insert booking header
            $sql = "INSERT INTO booking (nama_organisasi, nama_pic, no_telepon, tanggal_kedatangan, subtotal, diskon, total, dp, sisa, id_user) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $booking_id = insert($sql, [
                $nama_organisasi, 
                $nama_pic, 
                $no_telepon, 
                $tanggal_kedatangan, 
                $subtotal, 
                $diskon, 
                $total, 
                $dp, 
                $sisa, 
                $user_id
            ], 'ssssdddddi');
            
            // Insert booking details
            $sql_detail = "INSERT INTO booking_detail (id_booking, id_layanan, nama_layanan, quantity, harga, subtotal) 
                          VALUES (?, ?, ?, ?, ?, ?)";
            
            foreach ($items as $item) {
                $stmt = $conn->prepare($sql_detail);
                $stmt->bind_param('iisidd', 
                    $booking_id,
                    $item['id_layanan'],
                    $item['nama_layanan'],
                    $item['quantity'],
                    $item['harga'],
                    $item['subtotal']
                );
                $stmt->execute();
                $stmt->close();
            }
            
            $conn->commit();
            
            jsonResponse(true, 'Booking berhasil disimpan', ['id' => $booking_id]);
        } catch (Exception $e) {
            $conn->rollback();
            throw $e;
        }
        
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function updateBooking() {
    try {
        $id = intval($_POST['id'] ?? 0);
        $nama_organisasi = clean($_POST['nama_organisasi'] ?? '');
        $nama_pic = clean($_POST['nama_pic'] ?? '');
        $no_telepon = clean($_POST['no_telepon'] ?? '');
        $tanggal_kedatangan = clean($_POST['tanggal_kedatangan'] ?? '');
        $items = json_decode($_POST['items'] ?? '[]', true);
        $subtotal = floatval($_POST['subtotal'] ?? 0);
        $diskon = floatval($_POST['diskon'] ?? 0);
        $total = floatval($_POST['total'] ?? 0);
        $dp = floatval($_POST['dp'] ?? 0);
        $sisa = floatval($_POST['sisa'] ?? 0);
        
        // Validasi
        if ($id <= 0) {
            jsonResponse(false, 'ID booking tidak valid');
        }
        
        if (empty($nama_organisasi) || empty($nama_pic) || empty($no_telepon) || empty($tanggal_kedatangan)) {
            jsonResponse(false, 'Data organisasi tidak lengkap');
        }
        
        if (empty($items) || $subtotal <= 0) {
            jsonResponse(false, 'Minimal harus ada 1 item');
        }
        
        // Validasi tanggal
        if (strtotime($tanggal_kedatangan) < strtotime(date('Y-m-d'))) {
            jsonResponse(false, 'Tanggal kedatangan tidak boleh kurang dari hari ini');
        }
        
        // Validasi diskon
        if ($diskon > $subtotal) {
            jsonResponse(false, 'Diskon tidak boleh lebih dari subtotal');
        }
        
        // Validasi DP
        if ($dp > $total) {
            jsonResponse(false, 'DP tidak boleh lebih dari total');
        }
        
        $conn = getConnection();
        $conn->begin_transaction();
        
        try {
            // Update booking header
            $sql = "UPDATE booking SET 
                    nama_organisasi = ?, 
                    nama_pic = ?, 
                    no_telepon = ?, 
                    tanggal_kedatangan = ?, 
                    subtotal = ?, 
                    diskon = ?, 
                    total = ?, 
                    dp = ?, 
                    sisa = ? 
                    WHERE id = ?";
            execute($sql, [
                $nama_organisasi,
                $nama_pic,
                $no_telepon,
                $tanggal_kedatangan,
                $subtotal,
                $diskon,
                $total,
                $dp,
                $sisa,
                $id
            ], 'ssssddddddi');
            
            // Delete old details
            $sql_delete = "DELETE FROM booking_detail WHERE id_booking = ?";
            execute($sql_delete, [$id], 'i');
            
            // Insert new details
            $sql_detail = "INSERT INTO booking_detail (id_booking, id_layanan, nama_layanan, quantity, harga, subtotal) 
                          VALUES (?, ?, ?, ?, ?, ?)";
            
            foreach ($items as $item) {
                $stmt = $conn->prepare($sql_detail);
                $stmt->bind_param('iisidd', 
                    $id,
                    $item['id_layanan'],
                    $item['nama_layanan'],
                    $item['quantity'],
                    $item['harga'],
                    $item['subtotal']
                );
                $stmt->execute();
                $stmt->close();
            }
            
            $conn->commit();
            
            jsonResponse(true, 'Booking berhasil diupdate', ['id' => $id]);
        } catch (Exception $e) {
            $conn->rollback();
            throw $e;
        }
        
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function deleteBooking() {
    try {
        $id = intval($_POST['id'] ?? 0);
        
        if ($id <= 0) {
            jsonResponse(false, 'ID tidak valid');
        }
        
        // Cek booking exists
        $checkSql = "SELECT id FROM booking WHERE id = ?";
        $checkResult = query($checkSql, [$id], 'i');
        if ($checkResult->num_rows === 0) {
            jsonResponse(false, 'Booking tidak ditemukan');
        }
        
        // Delete booking (cascade akan delete detail)
        $sql = "DELETE FROM booking WHERE id = ?";
        execute($sql, [$id], 'i');
        
        jsonResponse(true, 'Booking berhasil dihapus');
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function getBookingList() {
    try {
        $dari = clean($_GET['dari'] ?? '');
        $sampai = clean($_GET['sampai'] ?? '');
        $search = clean($_GET['search'] ?? '');
        
        $sql = "SELECT b.*, u.nama as admin_nama 
                FROM booking b 
                JOIN users u ON b.id_user = u.id 
                WHERE 1=1";
        
        $params = [];
        $types = '';
        
        if (!empty($dari)) {
            $sql .= " AND b.tanggal_kedatangan >= ?";
            $params[] = $dari;
            $types .= 's';
        }
        
        if (!empty($sampai)) {
            $sql .= " AND b.tanggal_kedatangan <= ?";
            $params[] = $sampai;
            $types .= 's';
        }
        
        if (!empty($search)) {
            $sql .= " AND (b.nama_organisasi LIKE ? OR b.nama_pic LIKE ? OR b.no_telepon LIKE ?)";
            $searchTerm = "%$search%";
            $params[] = $searchTerm;
            $params[] = $searchTerm;
            $params[] = $searchTerm;
            $types .= 'sss';
        }
        
        $sql .= " ORDER BY b.tanggal_kedatangan DESC, b.created_at DESC";
        
        $result = query($sql, $params, $types);
        $bookings = [];
        while ($row = $result->fetch_assoc()) {
            $bookings[] = $row;
        }
        
        jsonResponse(true, 'Success', $bookings);
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function getBooking() {
    try {
        $id = intval($_GET['id'] ?? 0);
        
        if ($id <= 0) {
            jsonResponse(false, 'ID tidak valid');
        }
        
        // Get booking header
        $sql = "SELECT b.*, u.nama as admin_nama 
                FROM booking b 
                JOIN users u ON b.id_user = u.id 
                WHERE b.id = ?";
        $result = query($sql, [$id], 'i');
        
        if ($result->num_rows === 0) {
            jsonResponse(false, 'Booking tidak ditemukan');
        }
        
        $booking = $result->fetch_assoc();
        
        // Get booking details
        $sql_detail = "SELECT * FROM booking_detail WHERE id_booking = ?";
        $result_detail = query($sql_detail, [$id], 'i');
        
        $details = [];
        while ($row = $result_detail->fetch_assoc()) {
            $details[] = $row;
        }
        
        $booking['details'] = $details;
        
        jsonResponse(true, 'Success', $booking);
        
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}
?>
