<?php
/**
 * Staff Data API Handler
 * Provides AJAX endpoints for staff dashboard operations
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/session.php';
require_once __DIR__ . '/../config/helpers.php';
require_once __DIR__ . '/../config/mailer.php';

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

// Check if user is logged in and is staff
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$currentUser = getCurrentUser();
if (!isset($currentUser['user_type']) || $currentUser['user_type'] !== 'staff') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Forbidden']);
    exit();
}

$requestAction = $_GET['action'] ?? $_POST['action'] ?? '';
$action = sanitize($requestAction);

try {
    switch ($action) {
        case 'get_dashboard_stats':
            getDashboardStats();
            break;

        case 'get_today_checkins':
            getTodayCheckIns();
            break;

        case 'get_pending_reservations':
            getPendingReservations();
            break;

        case 'get_recent_reservations':
            getRecentReservations();
            break;

        case 'update_reservation_status':
            updateReservationStatus();
            break;

        case 'update_reservation_payment_status':
            updateReservationPaymentStatus();
            break;

        case 'update_service_reservation_status':
            updateServiceReservationStatus();
            break;

        case 'update_service_reservation_payment_status':
            updateServiceReservationPaymentStatus();
            break;

        case 'get_staff_profile':
            getStaffProfile();
            break;

        case 'update_staff_profile':
            updateStaffProfile();
            break;

        case 'change_staff_password':
            changeStaffPassword();
            break;

        case 'upload_profile_image':
            uploadProfileImage();
            break;

        case 'get_room_reservations':
            getRoomReservations();
            break;

        case 'get_service_reservations':
            getServiceReservations();
            break;

        default:
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
            break;
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error']);
    error_log($e->getMessage());
}

/**
 * Get dashboard statistics
 */
function getDashboardStats() {
    global $conn;

    $stats = [];

    try {
        // Total guests
        $result = $conn->query("SELECT COUNT(*) as count FROM users WHERE user_type = 'guest' AND is_active = 1");
        $stats['total_guests'] = $result ? $result->fetch_assoc()['count'] : 0;

        // Total reservations
        $result = $conn->query("SELECT COUNT(*) as count FROM reservations");
        $stats['total_reservations'] = $result ? $result->fetch_assoc()['count'] : 0;

        // Active reservations
        $result = $conn->query("SELECT COUNT(*) as count FROM reservations WHERE status IN ('pending', 'confirmed', 'checked_in')");
        $stats['active_reservations'] = $result ? $result->fetch_assoc()['count'] : 0;

        // Total service reservations
        $result = $conn->query("SELECT COUNT(*) as count FROM service_reservations");
        $stats['total_service_reservations'] = $result ? $result->fetch_assoc()['count'] : 0;

        // Active service reservations
        $result = $conn->query("SELECT COUNT(*) as count FROM service_reservations WHERE status IN ('pending', 'confirmed')");
        $stats['active_service_reservations'] = $result ? $result->fetch_assoc()['count'] : 0;

        // Checked-in guests
        $result = $conn->query("SELECT COUNT(*) as count FROM reservations WHERE status = 'checked_in'");
        $stats['checked_in_guests'] = $result ? $result->fetch_assoc()['count'] : 0;

        // Pending reservations
        $result = $conn->query("SELECT COUNT(*) as count FROM reservations WHERE status = 'pending'");
        $stats['pending_reservations'] = $result ? $result->fetch_assoc()['count'] : 0;

        // Pending service reservations
        $result = $conn->query("SELECT COUNT(*) as count FROM service_reservations WHERE status = 'pending'");
        $stats['pending_service_reservations'] = $result ? $result->fetch_assoc()['count'] : 0;

        // Total active bookings (room + service)
        $stats['total_active_bookings'] = (int)$stats['active_reservations'] + (int)$stats['active_service_reservations'];
        $stats['total_pending_reservations'] = (int)$stats['pending_reservations'] + (int)$stats['pending_service_reservations'];

        echo json_encode(['success' => true, 'data' => $stats]);
    } catch (Exception $e) {
        throw $e;
    }
}

/**
 * Get today's check-ins
 */
function getTodayCheckIns() {
    global $conn;

    try {
        $today = date('Y-m-d');
        $sql = "SELECT r.*, u.first_name, u.last_name, u.email, u.phone, rm.room_number, rm.room_type
                FROM reservations r
                LEFT JOIN users u ON r.user_id = u.id
                LEFT JOIN rooms rm ON r.room_id = rm.id
                WHERE DATE(r.check_in_date) = '$today'
                ORDER BY r.created_at DESC
                LIMIT 10";

        $result = $conn->query($sql);
        $checkins = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

        echo json_encode(['success' => true, 'data' => $checkins]);
    } catch (Exception $e) {
        throw $e;
    }
}

/**
 * Get pending reservations
 */
function getPendingReservations() {
    global $conn;

    try {
        $sql = "SELECT r.*, u.first_name, u.last_name, u.email, u.phone, rm.room_number, rm.room_type
                FROM reservations r
                LEFT JOIN users u ON r.user_id = u.id
                LEFT JOIN rooms rm ON r.room_id = rm.id
                WHERE r.status = 'pending'
                ORDER BY r.created_at DESC
                LIMIT 10";

        $result = $conn->query($sql);
        $reservations = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

        echo json_encode(['success' => true, 'data' => $reservations]);
    } catch (Exception $e) {
        throw $e;
    }
}

/**
 * Get recent reservations
 */
function getRecentReservations() {
    global $conn;

    try {
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
        $sql = "SELECT r.*, u.first_name, u.last_name, u.email, rm.room_number, rm.room_type
                FROM reservations r
                LEFT JOIN users u ON r.user_id = u.id
                LEFT JOIN rooms rm ON r.room_id = rm.id
                ORDER BY r.created_at DESC
                LIMIT $limit";

        $result = $conn->query($sql);
        $reservations = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];

        echo json_encode(['success' => true, 'data' => $reservations]);
    } catch (Exception $e) {
        throw $e;
    }
}

/**
 * Update reservation status
 */
function updateReservationStatus() {
    global $conn;

    $reservationId = isset($_POST['reservation_id']) ? (int)$_POST['reservation_id'] : 0;
    $newStatus = isset($_POST['status']) ? sanitize($_POST['status']) : '';

    if (!$reservationId || !$newStatus) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
        exit();
    }

    // Validate status
    $validStatuses = ['pending', 'confirmed', 'checked_in', 'checked_out', 'cancelled'];
    if (!in_array($newStatus, $validStatuses)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid status']);
        exit();
    }

    try {
        // Prevent changing terminal reservation statuses.
        $currentStatus = null;
        $statusStmt = $conn->prepare("SELECT status FROM reservations WHERE id = ? LIMIT 1");
        if ($statusStmt) {
            $statusStmt->bind_param('i', $reservationId);
            $statusStmt->execute();
            $statusResult = $statusStmt->get_result();
            if ($statusResult && $statusResult->num_rows > 0) {
                $statusRow = $statusResult->fetch_assoc();
                $currentStatus = strtolower((string)($statusRow['status'] ?? ''));
            }
            $statusStmt->close();
        }

        if ($currentStatus === null) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Reservation not found']);
            return;
        }

        if (in_array($currentStatus, ['checked_out', 'cancelled'], true) && $currentStatus !== $newStatus) {
            http_response_code(422);
            echo json_encode(['success' => false, 'message' => 'Checked-out/cancelled reservations cannot be changed']);
            return;
        }

        $stmt = $conn->prepare("UPDATE reservations SET status = ?, updated_at = NOW() WHERE id = ?");
        if ($stmt) {
            $stmt->bind_param('si', $newStatus, $reservationId);
            if ($stmt->execute()) {
                $affected = $stmt->affected_rows;

                if ($affected > 0 && in_array($newStatus, ['confirmed', 'checked_in', 'checked_out', 'cancelled'], true)) {
                    $detailsStmt = $conn->prepare(
                        "SELECT r.id, r.check_in_date, r.check_out_date, r.number_of_guests, r.total_price,
                                u.first_name, u.last_name, u.email,
                                rm.room_number, rm.room_type
                         FROM reservations r
                         LEFT JOIN users u ON r.user_id = u.id
                         LEFT JOIN rooms rm ON r.room_id = rm.id
                         WHERE r.id = ?
                         LIMIT 1"
                    );

                    if ($detailsStmt) {
                        $detailsStmt->bind_param('i', $reservationId);
                        $detailsStmt->execute();
                        $detailsResult = $detailsStmt->get_result();
                        $row = $detailsResult ? $detailsResult->fetch_assoc() : null;
                        $detailsStmt->close();

                        if ($row && !empty($row['email'])) {
                            $customerName = trim((string)($row['first_name'] ?? '') . ' ' . (string)($row['last_name'] ?? ''));
                            if ($customerName === '') {
                                $customerName = 'Guest';
                            }

                            $statusLabel = staffReservationStatusLabel($newStatus);
                            $subject = 'Your Zemaraim Room Reservation Status is now ' . $statusLabel;
                            $body = buildStaffReservationStatusEmailBody([
                                'guest_name' => $customerName,
                                'booking_id' => (string)$reservationId,
                                'status_label' => $statusLabel,
                                'room_number' => (string)($row['room_number'] ?? 'N/A'),
                                'room_type' => (string)($row['room_type'] ?? 'Room'),
                                'check_in' => (string)($row['check_in_date'] ?? '-'),
                                'check_out' => (string)($row['check_out_date'] ?? '-'),
                                'guests' => (string)($row['number_of_guests'] ?? '-'),
                                'total_price' => number_format((float)($row['total_price'] ?? 0), 2),
                            ]);
                            sendEmail((string)$row['email'], $customerName, $subject, $body);
                        }
                    }
                }

                echo json_encode(['success' => true, 'message' => 'Reservation status updated successfully']);
            } else {
                throw new Exception("Failed to update reservation");
            }
            $stmt->close();
        }
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error updating reservation']);
        throw $e;
    }
}

function staffReservationStatusLabel(string $status): string {
    $map = [
        'pending' => 'Pending',
        'confirmed' => 'Confirmed',
        'checked_in' => 'Checked In',
        'checked_out' => 'Checked Out',
        'cancelled' => 'Cancelled',
    ];

    return $map[$status] ?? ucfirst(str_replace('_', ' ', $status));
}

function buildStaffReservationStatusEmailBody(array $data): string {
    $guestName = htmlspecialchars((string)($data['guest_name'] ?? 'Guest'), ENT_QUOTES, 'UTF-8');
    $bookingId = htmlspecialchars((string)($data['booking_id'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $statusLabel = htmlspecialchars((string)($data['status_label'] ?? 'Updated'), ENT_QUOTES, 'UTF-8');
    $roomNumber = htmlspecialchars((string)($data['room_number'] ?? 'N/A'), ENT_QUOTES, 'UTF-8');
    $roomType = htmlspecialchars((string)($data['room_type'] ?? 'Room'), ENT_QUOTES, 'UTF-8');
    $checkIn = htmlspecialchars((string)($data['check_in'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $checkOut = htmlspecialchars((string)($data['check_out'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $guests = htmlspecialchars((string)($data['guests'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $totalPrice = htmlspecialchars((string)($data['total_price'] ?? '0.00'), ENT_QUOTES, 'UTF-8');

    return <<<HTML
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="font-family: Arial, sans-serif; color:#1f2937; background:#f5f7fb; margin:0; padding:20px;">
    <div style="max-width:680px; width:100%; margin:0 auto; background:#fff; border:1px solid #dbe5ef; border-radius:12px; overflow:hidden;">
        <div style="padding:18px 20px; background:#0f2942; color:#fff;">
            <h2 style="margin:0; font-size:20px;">Zemaraim Reservation Status Update</h2>
        </div>
        <div style="padding:20px;">
            <p style="margin-top:0;">Hello {$guestName}, your room reservation status has been updated.</p>
            <table style="width:100%; border-collapse:collapse;">
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Booking ID</td><td style="padding:8px 0;">#{$bookingId}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">New Status</td><td style="padding:8px 0;">{$statusLabel}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Room</td><td style="padding:8px 0;">{$roomNumber} ({$roomType})</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Check In</td><td style="padding:8px 0;">{$checkIn}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Check Out</td><td style="padding:8px 0;">{$checkOut}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Guests</td><td style="padding:8px 0;">{$guests}</td></tr>
            </table>
            <p style="margin-top:12px; padding:12px 14px; border:1px solid #cfe0f3; border-radius:10px; background:#f3f8fe;">
                <strong>Total Cost:</strong> \${$totalPrice}
            </p>
        </div>
    </div>
</body>
</html>
HTML;
}

/**
 * Update room reservation payment status
 */
function updateReservationPaymentStatus() {
    global $conn;
    ensureReservationPaymentColumn();

    $reservationId = isset($_POST['reservation_id']) ? (int)$_POST['reservation_id'] : 0;
    $paymentStatus = isset($_POST['payment_status']) ? sanitize($_POST['payment_status']) : '';

    if (!$reservationId || !$paymentStatus) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
        exit();
    }

    $validStatuses = ['unpaid', 'partial', 'paid'];
    if (!in_array($paymentStatus, $validStatuses, true)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid payment status']);
        exit();
    }

    try {
        // Staff cannot modify a reservation once payment is marked as paid.
        $currentPaymentStatus = null;
        $statusStmt = $conn->prepare("SELECT payment_status FROM reservations WHERE id = ? LIMIT 1");
        if ($statusStmt) {
            $statusStmt->bind_param('i', $reservationId);
            $statusStmt->execute();
            $statusResult = $statusStmt->get_result();
            if ($statusResult && $statusResult->num_rows > 0) {
                $statusRow = $statusResult->fetch_assoc();
                $currentPaymentStatus = strtolower((string)($statusRow['payment_status'] ?? 'unpaid'));
            }
            $statusStmt->close();
        }

        if ($currentPaymentStatus === null) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Reservation not found']);
            return;
        }

        if ($currentPaymentStatus === 'paid' && $paymentStatus !== 'paid') {
            http_response_code(422);
            echo json_encode(['success' => false, 'message' => 'Paid room reservations cannot be changed by staff']);
            return;
        }

        $stmt = $conn->prepare("UPDATE reservations SET payment_status = ?, updated_at = NOW() WHERE id = ?");
        if (!$stmt) {
            throw new Exception('Failed to prepare reservation payment update query');
        }

        $stmt->bind_param('si', $paymentStatus, $reservationId);
        if ($stmt->execute()) {
            $affected = $stmt->affected_rows;

            if ($affected > 0 && $paymentStatus === 'paid') {
                $detailsStmt = $conn->prepare(
                    "SELECT r.id, r.check_in_date, r.check_out_date, r.total_price, r.payment_status, r.updated_at,
                            u.first_name, u.last_name, u.email,
                            rm.room_number, rm.room_type
                     FROM reservations r
                     LEFT JOIN users u ON r.user_id = u.id
                     LEFT JOIN rooms rm ON r.room_id = rm.id
                     WHERE r.id = ?
                     LIMIT 1"
                );

                if ($detailsStmt) {
                    $detailsStmt->bind_param('i', $reservationId);
                    $detailsStmt->execute();
                    $detailsResult = $detailsStmt->get_result();
                    $row = $detailsResult ? $detailsResult->fetch_assoc() : null;
                    $detailsStmt->close();

                    if ($row && !empty($row['email'])) {
                        $customerName = trim((string)($row['first_name'] ?? '') . ' ' . (string)($row['last_name'] ?? ''));
                        if ($customerName === '') {
                            $customerName = 'Guest';
                        }

                        $subject = 'Payment Received for Your Zemaraim Room Reservation';
                        $body = buildStaffReservationPaymentEmailBody([
                            'guest_name' => $customerName,
                            'booking_id' => (string)$reservationId,
                            'room_number' => (string)($row['room_number'] ?? 'N/A'),
                            'room_type' => (string)($row['room_type'] ?? 'Room'),
                            'check_in' => (string)($row['check_in_date'] ?? '-'),
                            'check_out' => (string)($row['check_out_date'] ?? '-'),
                            'payment_status' => ucfirst((string)($row['payment_status'] ?? 'paid')),
                            'amount' => number_format((float)($row['total_price'] ?? 0), 2),
                            'updated_at' => (string)($row['updated_at'] ?? date('Y-m-d H:i:s')),
                        ]);
                        sendEmail((string)$row['email'], $customerName, $subject, $body);
                    }
                }
            }

            echo json_encode(['success' => true, 'message' => 'Reservation payment status updated successfully']);
        } else {
            throw new Exception('Failed to update reservation payment status');
        }
        $stmt->close();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error updating reservation payment status']);
        throw $e;
    }
}

/**
 * Update service reservation status
 */
function updateServiceReservationStatus() {
    global $conn;

    $serviceReservationId = isset($_POST['service_reservation_id']) ? (int)$_POST['service_reservation_id'] : 0;
    $newStatus = isset($_POST['status']) ? sanitize($_POST['status']) : '';

    if (!$serviceReservationId || !$newStatus) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
        exit();
    }

    $validStatuses = ['pending', 'confirmed', 'completed', 'cancelled'];
    if (!in_array($newStatus, $validStatuses, true)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid status']);
        exit();
    }

    try {
        // Prevent changing terminal service statuses.
        $currentStatus = null;
        $statusStmt = $conn->prepare("SELECT status FROM service_reservations WHERE id = ? LIMIT 1");
        if ($statusStmt) {
            $statusStmt->bind_param('i', $serviceReservationId);
            $statusStmt->execute();
            $statusResult = $statusStmt->get_result();
            if ($statusResult && $statusResult->num_rows > 0) {
                $statusRow = $statusResult->fetch_assoc();
                $currentStatus = strtolower((string)($statusRow['status'] ?? ''));
            }
            $statusStmt->close();
        }

        if ($currentStatus === null) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Service reservation not found']);
            return;
        }

        if (in_array($currentStatus, ['completed', 'cancelled'], true) && $currentStatus !== $newStatus) {
            http_response_code(422);
            echo json_encode(['success' => false, 'message' => 'Completed/cancelled service reservations cannot be changed']);
            return;
        }

        $stmt = $conn->prepare("UPDATE service_reservations SET status = ?, updated_at = NOW() WHERE id = ?");
        if (!$stmt) {
            throw new Exception("Failed to prepare service update query");
        }

        $stmt->bind_param('si', $newStatus, $serviceReservationId);
        if ($stmt->execute()) {
            $affected = $stmt->affected_rows;

            if ($affected > 0 && in_array($newStatus, ['confirmed', 'completed', 'cancelled'], true)) {
                $detailsStmt = $conn->prepare(
                    "SELECT sr.id, sr.service_start_date, sr.service_end_date, sr.number_of_guests, COALESCE(sr.total_price, 0) AS total_price,
                            u.first_name, u.last_name, u.email,
                            f.name AS service_name
                     FROM service_reservations sr
                     LEFT JOIN users u ON sr.user_id = u.id
                     LEFT JOIN facilities f ON sr.facility_id = f.id
                     WHERE sr.id = ?
                     LIMIT 1"
                );

                if ($detailsStmt) {
                    $detailsStmt->bind_param('i', $serviceReservationId);
                    $detailsStmt->execute();
                    $detailsResult = $detailsStmt->get_result();
                    $row = $detailsResult ? $detailsResult->fetch_assoc() : null;
                    $detailsStmt->close();

                    if ($row && !empty($row['email'])) {
                        $customerName = trim((string)($row['first_name'] ?? '') . ' ' . (string)($row['last_name'] ?? ''));
                        if ($customerName === '') {
                            $customerName = 'Guest';
                        }

                        $statusLabel = staffServiceReservationStatusLabel($newStatus);
                        $subject = 'Your Zemaraim Service Reservation Status is now ' . $statusLabel;
                        $body = buildStaffServiceReservationStatusEmailBody([
                            'guest_name' => $customerName,
                            'booking_id' => (string)$serviceReservationId,
                            'status_label' => $statusLabel,
                            'service_name' => (string)($row['service_name'] ?? 'Service'),
                            'start_date' => (string)($row['service_start_date'] ?? '-'),
                            'end_date' => (string)($row['service_end_date'] ?? '-'),
                            'guests' => (string)($row['number_of_guests'] ?? '-'),
                            'total_price' => number_format((float)($row['total_price'] ?? 0), 2),
                        ]);
                        sendEmail((string)$row['email'], $customerName, $subject, $body);
                    }
                }
            }

            echo json_encode(['success' => true, 'message' => 'Service reservation status updated successfully']);
        } else {
            throw new Exception("Failed to update service reservation");
        }
        $stmt->close();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error updating service reservation']);
        throw $e;
    }
}

function staffServiceReservationStatusLabel(string $status): string {
    $map = [
        'pending' => 'Pending',
        'confirmed' => 'Confirmed',
        'completed' => 'Completed',
        'cancelled' => 'Cancelled',
    ];

    return $map[$status] ?? ucfirst(str_replace('_', ' ', $status));
}

function buildStaffServiceReservationStatusEmailBody(array $data): string {
    $guestName = htmlspecialchars((string)($data['guest_name'] ?? 'Guest'), ENT_QUOTES, 'UTF-8');
    $bookingId = htmlspecialchars((string)($data['booking_id'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $statusLabel = htmlspecialchars((string)($data['status_label'] ?? 'Updated'), ENT_QUOTES, 'UTF-8');
    $serviceName = htmlspecialchars((string)($data['service_name'] ?? 'Service'), ENT_QUOTES, 'UTF-8');
    $startDate = htmlspecialchars((string)($data['start_date'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $endDate = htmlspecialchars((string)($data['end_date'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $guests = htmlspecialchars((string)($data['guests'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $totalPrice = htmlspecialchars((string)($data['total_price'] ?? '0.00'), ENT_QUOTES, 'UTF-8');

    return <<<HTML
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="font-family: Arial, sans-serif; color:#1f2937; background:#f5f7fb; margin:0; padding:20px;">
    <div style="max-width:680px; width:100%; margin:0 auto; background:#fff; border:1px solid #dbe5ef; border-radius:12px; overflow:hidden;">
        <div style="padding:18px 20px; background:#0f2942; color:#fff;">
            <h2 style="margin:0; font-size:20px;">Zemaraim Service Reservation Status Update</h2>
        </div>
        <div style="padding:20px;">
            <p style="margin-top:0;">Hello {$guestName}, your service reservation status has been updated.</p>
            <table style="width:100%; border-collapse:collapse;">
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Booking ID</td><td style="padding:8px 0;">#{$bookingId}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">New Status</td><td style="padding:8px 0;">{$statusLabel}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Service</td><td style="padding:8px 0;">{$serviceName}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Start Date</td><td style="padding:8px 0;">{$startDate}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">End Date</td><td style="padding:8px 0;">{$endDate}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Guests</td><td style="padding:8px 0;">{$guests}</td></tr>
            </table>
            <p style="margin-top:12px; padding:12px 14px; border:1px solid #cfe0f3; border-radius:10px; background:#f3f8fe;">
                <strong>Total Cost:</strong> \${$totalPrice}
            </p>
        </div>
    </div>
</body>
</html>
HTML;
}

/**
 * Update service reservation payment status
 */
function updateServiceReservationPaymentStatus() {
    global $conn;
    ensureServiceReservationPaymentColumn();

    $serviceReservationId = isset($_POST['service_reservation_id']) ? (int)$_POST['service_reservation_id'] : 0;
    $paymentStatus = isset($_POST['payment_status']) ? sanitize($_POST['payment_status']) : '';

    if (!$serviceReservationId || !$paymentStatus) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
        exit();
    }

    $validStatuses = ['unpaid', 'partial', 'paid'];
    if (!in_array($paymentStatus, $validStatuses, true)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid payment status']);
        exit();
    }

    try {
        // Once paid, payment status is terminal and cannot be changed again.
        $currentPaymentStatus = null;
        $statusStmt = $conn->prepare("SELECT payment_status FROM service_reservations WHERE id = ? LIMIT 1");
        if ($statusStmt) {
            $statusStmt->bind_param('i', $serviceReservationId);
            $statusStmt->execute();
            $statusResult = $statusStmt->get_result();
            if ($statusResult && $statusResult->num_rows > 0) {
                $statusRow = $statusResult->fetch_assoc();
                $currentPaymentStatus = strtolower((string)($statusRow['payment_status'] ?? 'unpaid'));
            }
            $statusStmt->close();
        }

        if ($currentPaymentStatus === null) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Service reservation not found']);
            return;
        }

        if ($currentPaymentStatus === 'paid' && $paymentStatus !== 'paid') {
            http_response_code(422);
            echo json_encode(['success' => false, 'message' => 'Paid service reservations cannot be changed']);
            return;
        }

        $stmt = $conn->prepare("UPDATE service_reservations SET payment_status = ?, updated_at = NOW() WHERE id = ?");
        if (!$stmt) {
            throw new Exception("Failed to prepare payment update query");
        }

        $stmt->bind_param('si', $paymentStatus, $serviceReservationId);
        if ($stmt->execute()) {
            $affected = $stmt->affected_rows;

            if ($affected > 0 && $paymentStatus === 'paid') {
                $detailsStmt = $conn->prepare(
                    "SELECT sr.id, sr.service_start_date, sr.service_end_date, sr.payment_status, sr.updated_at, COALESCE(sr.total_price, 0) AS total_price,
                            u.first_name, u.last_name, u.email,
                            f.name AS service_name
                     FROM service_reservations sr
                     LEFT JOIN users u ON sr.user_id = u.id
                     LEFT JOIN facilities f ON sr.facility_id = f.id
                     WHERE sr.id = ?
                     LIMIT 1"
                );

                if ($detailsStmt) {
                    $detailsStmt->bind_param('i', $serviceReservationId);
                    $detailsStmt->execute();
                    $detailsResult = $detailsStmt->get_result();
                    $row = $detailsResult ? $detailsResult->fetch_assoc() : null;
                    $detailsStmt->close();

                    if ($row && !empty($row['email'])) {
                        $customerName = trim((string)($row['first_name'] ?? '') . ' ' . (string)($row['last_name'] ?? ''));
                        if ($customerName === '') {
                            $customerName = 'Guest';
                        }

                        $subject = 'Payment Received for Your Zemaraim Service Reservation';
                        $body = buildStaffServiceReservationPaymentEmailBody([
                            'guest_name' => $customerName,
                            'booking_id' => (string)$serviceReservationId,
                            'service_name' => (string)($row['service_name'] ?? 'Service'),
                            'start_date' => (string)($row['service_start_date'] ?? '-'),
                            'end_date' => (string)($row['service_end_date'] ?? '-'),
                            'payment_status' => ucfirst((string)($row['payment_status'] ?? 'paid')),
                            'amount' => number_format((float)($row['total_price'] ?? 0), 2),
                            'updated_at' => (string)($row['updated_at'] ?? date('Y-m-d H:i:s')),
                        ]);
                        sendEmail((string)$row['email'], $customerName, $subject, $body);
                    }
                }
            }

            echo json_encode(['success' => true, 'message' => 'Service payment status updated successfully']);
        } else {
            throw new Exception("Failed to update service payment status");
        }
        $stmt->close();
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error updating service payment status']);
        throw $e;
    }
}

function buildStaffReservationPaymentEmailBody(array $data): string {
    $guestName = htmlspecialchars((string)($data['guest_name'] ?? 'Guest'), ENT_QUOTES, 'UTF-8');
    $bookingId = htmlspecialchars((string)($data['booking_id'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $roomNumber = htmlspecialchars((string)($data['room_number'] ?? 'N/A'), ENT_QUOTES, 'UTF-8');
    $roomType = htmlspecialchars((string)($data['room_type'] ?? 'Room'), ENT_QUOTES, 'UTF-8');
    $checkIn = htmlspecialchars((string)($data['check_in'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $checkOut = htmlspecialchars((string)($data['check_out'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $paymentStatus = htmlspecialchars((string)($data['payment_status'] ?? 'Paid'), ENT_QUOTES, 'UTF-8');
    $amount = htmlspecialchars((string)($data['amount'] ?? '0.00'), ENT_QUOTES, 'UTF-8');
    $updatedAt = htmlspecialchars((string)($data['updated_at'] ?? date('Y-m-d H:i:s')), ENT_QUOTES, 'UTF-8');

    return <<<HTML
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="font-family: Arial, sans-serif; color:#1f2937; background:#f5f7fb; margin:0; padding:20px;">
    <div style="max-width:680px; width:100%; margin:0 auto; background:#fff; border:1px solid #dbe5ef; border-radius:12px; overflow:hidden;">
        <div style="padding:18px 20px; background:#0f2942; color:#fff;">
            <h2 style="margin:0; font-size:20px;">Zemaraim Payment Confirmation</h2>
        </div>
        <div style="padding:20px;">
            <p style="margin-top:0;">Hello {$guestName}, your room reservation payment has been updated.</p>
            <table style="width:100%; border-collapse:collapse;">
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Booking ID</td><td style="padding:8px 0;">#{$bookingId}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Room</td><td style="padding:8px 0;">{$roomNumber} ({$roomType})</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Check In</td><td style="padding:8px 0;">{$checkIn}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Check Out</td><td style="padding:8px 0;">{$checkOut}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Payment Status</td><td style="padding:8px 0;">{$paymentStatus}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Updated At</td><td style="padding:8px 0;">{$updatedAt}</td></tr>
            </table>
            <p style="margin:12px 0 0; padding:12px 14px; border:1px solid #cfe0f3; border-radius:10px; background:#f3f8fe;">
                <strong>Paid Amount:</strong> \${$amount}
            </p>
        </div>
    </div>
</body>
</html>
HTML;
}

function buildStaffServiceReservationPaymentEmailBody(array $data): string {
    $guestName = htmlspecialchars((string)($data['guest_name'] ?? 'Guest'), ENT_QUOTES, 'UTF-8');
    $bookingId = htmlspecialchars((string)($data['booking_id'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $serviceName = htmlspecialchars((string)($data['service_name'] ?? 'Service'), ENT_QUOTES, 'UTF-8');
    $startDate = htmlspecialchars((string)($data['start_date'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $endDate = htmlspecialchars((string)($data['end_date'] ?? '-'), ENT_QUOTES, 'UTF-8');
    $paymentStatus = htmlspecialchars((string)($data['payment_status'] ?? 'Paid'), ENT_QUOTES, 'UTF-8');
    $amount = htmlspecialchars((string)($data['amount'] ?? '0.00'), ENT_QUOTES, 'UTF-8');
    $updatedAt = htmlspecialchars((string)($data['updated_at'] ?? date('Y-m-d H:i:s')), ENT_QUOTES, 'UTF-8');

    return <<<HTML
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="font-family: Arial, sans-serif; color:#1f2937; background:#f5f7fb; margin:0; padding:20px;">
    <div style="max-width:680px; width:100%; margin:0 auto; background:#fff; border:1px solid #dbe5ef; border-radius:12px; overflow:hidden;">
        <div style="padding:18px 20px; background:#0f2942; color:#fff;">
            <h2 style="margin:0; font-size:20px;">Zemaraim Service Payment Confirmation</h2>
        </div>
        <div style="padding:20px;">
            <p style="margin-top:0;">Hello {$guestName}, your service reservation payment has been updated.</p>
            <table style="width:100%; border-collapse:collapse;">
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Booking ID</td><td style="padding:8px 0;">#{$bookingId}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Service</td><td style="padding:8px 0;">{$serviceName}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Start Date</td><td style="padding:8px 0;">{$startDate}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">End Date</td><td style="padding:8px 0;">{$endDate}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Payment Status</td><td style="padding:8px 0;">{$paymentStatus}</td></tr>
                <tr><td style="padding:8px 0; color:#607286; font-weight:600;">Updated At</td><td style="padding:8px 0;">{$updatedAt}</td></tr>
            </table>
            <p style="margin:12px 0 0; padding:12px 14px; border:1px solid #cfe0f3; border-radius:10px; background:#f3f8fe;">
                <strong>Paid Amount:</strong> \${$amount}
            </p>
        </div>
    </div>
</body>
</html>
HTML;
}

/**
 * Get staff profile
 */
function getStaffProfile() {
    global $conn;

    $userId = getCurrentUserId();

    try {
        $stmt = $conn->prepare("SELECT id, first_name, last_name, email, phone, profile_picture, created_at FROM users WHERE id = ? AND user_type = 'staff'");
        if ($stmt) {
            $stmt->bind_param('i', $userId);
            $stmt->execute();
            $result = $stmt->get_result();
            $profile = $result ? $result->fetch_assoc() : null;
            $stmt->close();

            if ($profile) {
                $profilePicture = trim((string)($profile['profile_picture'] ?? ''));
                if ($profilePicture !== '' && !preg_match('/^https?:\/\//i', $profilePicture)) {
                    $profilePicture = str_replace('\\', '/', $profilePicture);
                }
                $profile['profile_picture'] = $profilePicture;

                echo json_encode(['success' => true, 'data' => $profile]);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Profile not found']);
            }
        }
    } catch (Exception $e) {
        throw $e;
    }
}

/**
 * Upload staff profile image
 */
function uploadProfileImage() {
    global $conn;

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        return;
    }

    $userId = getCurrentUserId();
    if ($userId <= 0) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        return;
    }

    if (!isset($_FILES['profile_image']) || !is_array($_FILES['profile_image'])) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Please choose an image file']);
        return;
    }

    $file = $_FILES['profile_image'];
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'No image file was uploaded']);
        return;
    }

    if (($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Image upload failed. Please try again']);
        return;
    }

    $tmp = (string)($file['tmp_name'] ?? '');
    if ($tmp === '' || !is_uploaded_file($tmp)) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Invalid uploaded image']);
        return;
    }

    $extension = strtolower(pathinfo((string)($file['name'] ?? ''), PATHINFO_EXTENSION));
    $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    if (!in_array($extension, $allowed, true)) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Only JPG, JPEG, PNG, WEBP, and GIF images are allowed']);
        return;
    }

    $maxSize = 5 * 1024 * 1024;
    if ((int)($file['size'] ?? 0) > $maxSize) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Image size must be less than 5MB']);
        return;
    }

    $uploadRoot = realpath(__DIR__ . '/..');
    if ($uploadRoot === false) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Upload directory resolution failed']);
        return;
    }

    $relativeDir = 'images/profiles';
    $absoluteDir = $uploadRoot . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'profiles';
    if (!is_dir($absoluteDir) && !mkdir($absoluteDir, 0775, true) && !is_dir($absoluteDir)) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Unable to create profile image directory']);
        return;
    }

    $fileName = 'staff-' . $userId . '-' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.' . $extension;
    $destination = $absoluteDir . DIRECTORY_SEPARATOR . $fileName;

    if (!move_uploaded_file($tmp, $destination)) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Unable to save uploaded image']);
        return;
    }

    $relativePath = str_replace('\\', '/', $relativeDir . '/' . $fileName);

    try {
        $stmt = $conn->prepare("UPDATE users SET profile_picture = ?, updated_at = NOW() WHERE id = ? AND user_type = 'staff'");
        if (!$stmt) {
            throw new Exception('Failed to prepare profile image update query');
        }
        $stmt->bind_param('si', $relativePath, $userId);
        $ok = $stmt->execute();
        $stmt->close();

        if (!$ok) {
            throw new Exception('Failed to update profile image');
        }

        if (session_status() === PHP_SESSION_ACTIVE) {
            if (!isset($_SESSION['user_data']) || !is_array($_SESSION['user_data'])) {
                $_SESSION['user_data'] = [];
            }
            $_SESSION['user_data']['profile_picture'] = $relativePath;
        }

        echo json_encode([
            'success' => true,
            'message' => 'Profile image uploaded successfully',
            'data' => [
                'image_url' => $relativePath
            ]
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error updating profile image']);
        throw $e;
    }
}

/**
 * Get room reservations
 */
function getRoomReservations() {
    global $conn;

    try {
        ensureReservationPaymentColumn();
        $status = isset($_GET['status']) ? sanitize($_GET['status']) : 'all';
        
        $sql = "SELECT r.id, u.first_name, u.last_name, u.email, u.phone, 
                rm.room_number, rm.room_type, r.check_in_date, r.check_out_date, 
                r.number_of_guests, r.total_price, COALESCE(r.payment_status, 'unpaid') AS payment_status, r.status
                FROM reservations r
                LEFT JOIN users u ON r.user_id = u.id
                LEFT JOIN rooms rm ON r.room_id = rm.id";

        if ($status !== 'all' && $status !== '') {
            $sql .= " WHERE r.status = '" . $conn->real_escape_string($status) . "'";
        }

        $sql .= " ORDER BY r.created_at DESC LIMIT 50";

        $result = $conn->query($sql);
        $reservations = [];

        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $reservations[] = [
                    'id' => $row['id'],
                    'guest_name' => trim($row['first_name'] . ' ' . $row['last_name']),
                    'email' => $row['email'],
                    'phone' => $row['phone'],
                    'room_number' => $row['room_number'],
                    'room_type' => $row['room_type'],
                    'check_in_date' => $row['check_in_date'],
                    'check_out_date' => $row['check_out_date'],
                    'number_of_guests' => $row['number_of_guests'],
                    'total_price' => $row['total_price'] ?? 0,
                    'payment_status' => $row['payment_status'] ?? 'unpaid',
                    'status' => $row['status']
                ];
            }
        }

        echo json_encode(['success' => true, 'data' => $reservations]);
    } catch (Exception $e) {
        throw $e;
    }
}

/**
 * Get service reservations
 */
function getServiceReservations() {
    global $conn;

    try {
        ensureServiceReservationPaymentColumn();
        $status = isset($_GET['status']) ? sanitize($_GET['status']) : 'all';

        $hasReservationDate = false;
        $hasReservationTime = false;
        $hasServiceStartDate = false;
        $hasServiceEndDate = false;

        $col = $conn->query("SHOW COLUMNS FROM service_reservations LIKE 'reservation_date'");
        $hasReservationDate = $col && $col->num_rows > 0;
        $col = $conn->query("SHOW COLUMNS FROM service_reservations LIKE 'reservation_time'");
        $hasReservationTime = $col && $col->num_rows > 0;
        $col = $conn->query("SHOW COLUMNS FROM service_reservations LIKE 'service_start_date'");
        $hasServiceStartDate = $col && $col->num_rows > 0;
        $col = $conn->query("SHOW COLUMNS FROM service_reservations LIKE 'service_end_date'");
        $hasServiceEndDate = $col && $col->num_rows > 0;

        $reservationDateExpr = $hasReservationDate
            ? "sr.reservation_date"
            : ($hasServiceStartDate ? "sr.service_start_date" : "NULL");
        $reservationTimeExpr = $hasReservationTime ? "sr.reservation_time" : "NULL";
        $serviceStartExpr = $hasServiceStartDate ? "sr.service_start_date" : "NULL";
        $serviceEndExpr = $hasServiceEndDate ? "sr.service_end_date" : "NULL";

        $sql = "SELECT sr.id, u.first_name, u.last_name, u.email, u.phone,
                f.name as service_name,
                $reservationDateExpr AS reservation_date,
                $reservationTimeExpr AS reservation_time,
                $serviceStartExpr AS service_start_date,
                $serviceEndExpr AS service_end_date,
                COALESCE(sr.total_price, 0) AS total_price,
                COALESCE(sr.payment_status, 'unpaid') AS payment_status,
                sr.status
                FROM service_reservations sr
                LEFT JOIN users u ON sr.user_id = u.id
                LEFT JOIN facilities f ON sr.facility_id = f.id";

        if ($status !== 'all' && $status !== '') {
            $sql .= " WHERE sr.status = '" . $conn->real_escape_string($status) . "'";
        }

        $sql .= " ORDER BY sr.created_at DESC LIMIT 50";

        $result = $conn->query($sql);
        $services = [];

        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $services[] = [
                    'id' => $row['id'],
                    'guest_name' => trim($row['first_name'] . ' ' . $row['last_name']),
                    'email' => $row['email'],
                    'phone' => $row['phone'],
                    'service_name' => $row['service_name'],
                    'reservation_date' => $row['reservation_date'],
                    'reservation_time' => $row['reservation_time'],
                    'service_start_date' => $row['service_start_date'] ?? null,
                    'service_end_date' => $row['service_end_date'] ?? null,
                    'total_price' => $row['total_price'] ?? 0,
                    'payment_status' => $row['payment_status'] ?? 'unpaid',
                    'status' => $row['status']
                ];
            }
        }

        echo json_encode(['success' => true, 'data' => $services]);
    } catch (Exception $e) {
        throw $e;
    }
}

/**
 * Sanitize input
 */
function sanitize($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

/**
 * Update staff profile details
 */
function updateStaffProfile() {
    global $conn;

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        return;
    }

    $userId = getCurrentUserId();
    $firstName = trim((string)($_POST['first_name'] ?? ''));
    $lastName = trim((string)($_POST['last_name'] ?? ''));
    $email = trim((string)($_POST['email'] ?? ''));
    $phone = trim((string)($_POST['phone'] ?? ''));

    if ($userId <= 0 || $firstName === '' || $lastName === '' || $email === '') {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'First name, last name and email are required']);
        return;
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Invalid email address']);
        return;
    }

    try {
        $checkStmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ? LIMIT 1");
        if (!$checkStmt) {
            throw new Exception('Failed to prepare email uniqueness check');
        }
        $checkStmt->bind_param('si', $email, $userId);
        $checkStmt->execute();
        $checkResult = $checkStmt->get_result();
        if ($checkResult && $checkResult->num_rows > 0) {
            $checkStmt->close();
            http_response_code(422);
            echo json_encode(['success' => false, 'message' => 'Email is already in use']);
            return;
        }
        $checkStmt->close();

        $stmt = $conn->prepare("UPDATE users SET first_name = ?, last_name = ?, email = ?, phone = ?, updated_at = NOW() WHERE id = ? AND user_type = 'staff'");
        if (!$stmt) {
            throw new Exception('Failed to prepare profile update query');
        }
        $stmt->bind_param('ssssi', $firstName, $lastName, $email, $phone, $userId);
        $ok = $stmt->execute();
        $stmt->close();

        if (!$ok) {
            throw new Exception('Failed to update profile');
        }

        if (session_status() === PHP_SESSION_ACTIVE) {
            if (!isset($_SESSION['user_data']) || !is_array($_SESSION['user_data'])) {
                $_SESSION['user_data'] = [];
            }
            $_SESSION['user_data']['first_name'] = $firstName;
            $_SESSION['user_data']['last_name'] = $lastName;
            $_SESSION['user_data']['email'] = $email;
            $_SESSION['email'] = $email;
        }

        echo json_encode([
            'success' => true,
            'message' => 'Profile updated successfully',
            'data' => [
                'first_name' => $firstName,
                'last_name' => $lastName,
                'email' => $email,
                'phone' => $phone
            ]
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error updating profile']);
        throw $e;
    }
}

/**
 * Change staff account password
 */
function changeStaffPassword() {
    global $conn;

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        return;
    }

    $userId = getCurrentUserId();
    $currentPassword = (string)($_POST['current_password'] ?? '');
    $newPassword = (string)($_POST['new_password'] ?? '');
    $confirmPassword = (string)($_POST['confirm_password'] ?? '');

    if ($userId <= 0 || $currentPassword === '' || $newPassword === '' || $confirmPassword === '') {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'All password fields are required']);
        return;
    }

    if (strlen($newPassword) < 8) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'New password must be at least 8 characters']);
        return;
    }

    if ($newPassword !== $confirmPassword) {
        http_response_code(422);
        echo json_encode(['success' => false, 'message' => 'Password confirmation does not match']);
        return;
    }

    try {
        $stmt = $conn->prepare("SELECT password FROM users WHERE id = ? AND user_type = 'staff' LIMIT 1");
        if (!$stmt) {
            throw new Exception('Failed to prepare current password query');
        }
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $result = $stmt->get_result();
        $user = $result ? $result->fetch_assoc() : null;
        $stmt->close();

        if (!$user) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Staff account not found']);
            return;
        }

        $storedPassword = (string)($user['password'] ?? '');
        if (!password_verify($currentPassword, $storedPassword)) {
            http_response_code(422);
            echo json_encode(['success' => false, 'message' => 'Current password is incorrect']);
            return;
        }

        if (password_verify($newPassword, $storedPassword)) {
            http_response_code(422);
            echo json_encode(['success' => false, 'message' => 'New password must be different from current password']);
            return;
        }

        $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
        $updateStmt = $conn->prepare("UPDATE users SET password = ?, updated_at = NOW() WHERE id = ? AND user_type = 'staff'");
        if (!$updateStmt) {
            throw new Exception('Failed to prepare password update query');
        }
        $updateStmt->bind_param('si', $newHash, $userId);
        $ok = $updateStmt->execute();
        $updateStmt->close();

        if (!$ok) {
            throw new Exception('Failed to update password');
        }

        echo json_encode(['success' => true, 'message' => 'Password changed successfully']);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Error changing password']);
        throw $e;
    }
}

function ensureServiceReservationPaymentColumn() {
    global $conn;

    $check = $conn->query("SHOW COLUMNS FROM service_reservations LIKE 'payment_status'");
    if ($check && $check->num_rows > 0) {
        return;
    }

    $conn->query("ALTER TABLE service_reservations ADD COLUMN payment_status ENUM('unpaid', 'partial', 'paid') DEFAULT 'unpaid' AFTER total_price");
}

function ensureReservationPaymentColumn() {
    global $conn;

    $check = $conn->query("SHOW COLUMNS FROM reservations LIKE 'payment_status'");
    if ($check && $check->num_rows > 0) {
        return;
    }

    $conn->query("ALTER TABLE reservations ADD COLUMN payment_status ENUM('unpaid', 'partial', 'paid') DEFAULT 'unpaid' AFTER total_price");
}
?>
