File "update_booking_status.php"

Full path: /home/itsevak/public_html/prepaiddev.itsevak.com/operator/update_booking_status.php
File size: 7.08 B (7.08 KB bytes)
MIME-type: text/x-php
Charset: utf-8

Download   Open   Edit   Advanced Editor   Back

<?php
require_once '../includes/functions.php';


error_log('update_booking_status.php accessed');
error_log('POST data: ' . print_r($_POST, true));

// Require login and operator access
requireLogin();
if ($_SESSION['user_type'] !== 'operator') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

// Check if it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Validate CSRF token
$csrfToken = $_POST['csrf_token'] ?? '';
error_log('CSRF token received: ' . $csrfToken);
if (!validateCSRFToken($csrfToken)) {
    error_log('CSRF token validation failed');
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid CSRF token']);
    exit;
}
error_log('CSRF token validation passed');

// Get and validate input
$bookingId = $_POST['booking_id'] ?? '';
$status = $_POST['status'] ?? '';

error_log('Booking ID: ' . $bookingId . ', Status: ' . $status);

if (empty($bookingId) || empty($status)) {
    error_log('Missing required parameters');
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required parameters']);
    exit;
}

// Validate status
error_log('Validating status: ' . $status);
if (!in_array($status, ['completed', 'cancelled'])) {
    error_log('Invalid status: ' . $status);
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid status. Only completed or cancelled allowed.']);
    exit;
}
error_log('Status validation passed');

try {
    error_log('Starting database operations');
    $db = Database::getInstance();
    $user = getCurrentUser();
    error_log('User ID: ' . $user['id']);
    
    // Check if operator has active session
    $currentSession = $db->fetch(
        "SELECT * FROM operator_sessions WHERE operator_id = ? AND status = 'active'",
        [$user['id']]
    );
    
    if (!$currentSession) {
        error_log('No active operator session found');
        http_response_code(403);
        echo json_encode(['success' => false, 'message' => 'No active operator session']);
        exit;
    }
    error_log('Active session found: ' . $currentSession['id']);
    
    // Get the current booking to verify it exists and belongs to this operator
    $booking = $db->fetch(
        "SELECT * FROM bookings WHERE id = ? AND operator_id = ?",
        [$bookingId, $user['id']]
    );
    
    if (!$booking) {
        error_log('Booking not found: ID=' . $bookingId . ', Operator=' . $user['id']);
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Booking not found or not accessible']);
        exit;
    }
    
    error_log('Booking found with status: ' . $booking['status']);
    
    // Check if the status change is valid
    if ($status === 'cancelled' && $booking['status'] !== 'in_progress') {
        error_log('Cannot cancel booking with status: ' . $booking['status']);
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Cannot cancel booking with status: ' . $booking['status']]);
        exit;
    }
    
    if ($status === 'completed' && $booking['status'] !== 'in_progress') {
        error_log('Cannot complete booking with status: ' . $booking['status']);
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Cannot complete booking with status: ' . $booking['status']]);
        exit;
    }
    
    error_log('Status change validation passed');
    
    // Update the booking status
    if ($status === 'completed') {
        $db->query(
            "UPDATE bookings SET status = ?, completion_time = NOW() WHERE id = ?",
            [$status, $bookingId]
        );
    } else {
        // For cancelled status, try to set cancellation_time if column exists, otherwise just update status
        try {
            $db->query(
                "UPDATE bookings SET status = ?, cancellation_time = NOW() WHERE id = ?",
                [$status, $bookingId]
            );
        } catch (Exception $e) {
            // If cancellation_time column doesn't exist, just update the status
            error_log('Cancellation time column not available, updating status only: ' . $e->getMessage());
            $db->query(
                "UPDATE bookings SET status = ? WHERE id = ?",
                [$status, $bookingId]
            );
        }
    }
    
    // Verify the update was successful
    $updatedBooking = $db->fetch("SELECT status FROM bookings WHERE id = ?", [$bookingId]);
    if (!$updatedBooking || $updatedBooking['status'] !== $status) {
        throw new Exception('Failed to update booking status. Expected: ' . $status . ', Got: ' . ($updatedBooking['status'] ?? 'null'));
    }
    
    // Log the status change (optional - table may not exist)
    try {
        $db->query(
            "INSERT INTO booking_status_logs (booking_id, operator_id, old_status, new_status, changed_at) VALUES (?, ?, ?, ?, NOW())",
            [$bookingId, $user['id'], $booking['status'], $status]
        );
    } catch (Exception $e) {
        // Log table doesn't exist, continue without logging
        error_log('Status logging table not available: ' . $e->getMessage());
    }
    
    // Update operator session stats (optional - column may not exist)
    try {
        if ($status === 'completed') {
            $db->query(
                "UPDATE operator_sessions SET completed_bookings = completed_bookings + 1 WHERE id = ?",
                [$currentSession['id']]
            );
        } else {
            // For cancelled status, try to update cancelled_bookings if column exists
            try {
                $db->query(
                    "UPDATE operator_sessions SET cancelled_bookings = cancelled_bookings + 1 WHERE id = ?",
                    [$currentSession['id']]
                );
            } catch (Exception $e) {
                // cancelled_bookings column doesn't exist, skip this update
                error_log('Cancelled bookings column not available: ' . $e->getMessage());
            }
        }
    } catch (Exception $e) {
        // Stats columns don't exist, continue without updating
        error_log('Session stats columns not available: ' . $e->getMessage());
    }
    
    error_log('Successfully updated booking status to: ' . $status);
    echo json_encode([
        'success' => true, 
        'message' => 'Booking status updated successfully',
        'booking_id' => $bookingId,
        'new_status' => $status,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    error_log('Error updating booking status: ' . $e->getMessage());
    error_log('Booking ID: ' . $bookingId . ', Status: ' . $status . ', User ID: ' . $user['id']);
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal server error: ' . $e->getMessage()]);
}
?>