<?php
require_once '../auth.php';
ensureAdminAjaxAuth();
// ajax/quick_update_status.php
require_once '../../config/database.php';
require_once '../../includes/app_helpers.php';

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

if($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();
    ensureOperationalTables($db);
    
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $status_id = isset($_POST['status_id']) ? intval($_POST['status_id']) : 0;
    
    if(!$id || !$status_id) {
        echo json_encode(['success' => false, 'message' => 'Required fields missing']);
        exit;
    }
    
    // Get current status for history
    $current_query = "SELECT job_status_id, request_number FROM service_requests WHERE id = :id";
    $current_stmt = $db->prepare($current_query);
    $current_stmt->execute([':id' => $id]);
    $current = $current_stmt->fetch(PDO::FETCH_ASSOC);
    
    if(!$current) {
        echo json_encode(['success' => false, 'message' => 'Request not found']);
        exit;
    }
    
    // Don't update if status is the same
    if($current['job_status_id'] == $status_id) {
        echo json_encode(['success' => true, 'message' => 'Status unchanged']);
        exit;
    }
    
    // Update the status
    $query = "UPDATE service_requests SET job_status_id = :status_id WHERE id = :id";
    $stmt = $db->prepare($query);
    $result = $stmt->execute([
        ':id' => $id,
        ':status_id' => $status_id
    ]);
    
    if($result) {
        // Add to status history
        $history_query = "INSERT INTO request_status_history 
                         (request_id, job_status_id, notes, changed_by) 
                         VALUES (:request_id, :status_id, :notes, :changed_by)";
        $history_stmt = $db->prepare($history_query);
        $history_stmt->execute([
            ':request_id' => $id,
            ':status_id' => $status_id,
            ':notes' => 'Status updated via quick action',
            ':changed_by' => $_SESSION['admin_name'] ?? 'Admin'
        ]);
        
        try { logRequestAction($db, $id, $_SESSION['admin_id'] ?? null, 'admin', 'status_change', $current['job_status_id'], $status_id, 'Status updated via quick action'); } catch (Exception $logEx) { error_log('admin quick status log warning: ' . $logEx->getMessage()); }
        // If status is completed, set completed_date
        if($status_id == 4) { // Assuming 4 is Completed
            $complete_query = "UPDATE service_requests SET completed_date = NOW() WHERE id = :id";
            $complete_stmt = $db->prepare($complete_query);
            $complete_stmt->execute([':id' => $id]);
        }
        
        // Get new status info
        $status_query = "SELECT id, status_name, color_code FROM job_statuses WHERE id = :id";
        $status_stmt = $db->prepare($status_query);
        $status_stmt->execute([':id' => $status_id]);
        $new_status = $status_stmt->fetch(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'message' => 'Status updated successfully',
            'new_status' => [
                'id' => $new_status['id'],
                'name' => $new_status['status_name'],
                'color' => $new_status['color_code']
            ]
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating status']);
    }
    
} catch(Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>