<?php
require_once '../auth.php';
ensureAdminAjaxAuth();
// ajax/update_request.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;
    $urgency_id = isset($_POST['urgency_id']) ? intval($_POST['urgency_id']) : null;
    $brand_id = isset($_POST['brand_id']) ? intval($_POST['brand_id']) : null;
    $appliance_id = isset($_POST['appliance_id']) ? intval($_POST['appliance_id']) : null;
    $model_number = isset($_POST['model_number']) ? trim($_POST['model_number']) : null;
    $serial_number = isset($_POST['serial_number']) ? trim($_POST['serial_number']) : null;
    $full_name = isset($_POST['full_name']) ? trim($_POST['full_name']) : '';
    $phone_number = isset($_POST['phone_number']) ? trim($_POST['phone_number']) : '';
    $service_address = isset($_POST['service_address']) ? trim($_POST['service_address']) : '';
    $issue_description = isset($_POST['issue_description']) ? trim($_POST['issue_description']) : '';
    $update_notes = isset($_POST['update_notes']) ? trim($_POST['update_notes']) : '';
    
    if(!$id || !$status_id) {
        echo json_encode(['success' => false, 'message' => 'Required fields missing']);
        exit;
    }
    
    // Get current status for history
    $current_query = "SELECT * FROM service_requests WHERE id = :id";
    $current_stmt = $db->prepare($current_query);
    $current_stmt->execute([':id' => $id]);
    $current = $current_stmt->fetch(PDO::FETCH_ASSOC);
    
    // Update the request
    $query = "UPDATE service_requests SET 
                job_status_id = :status_id,
                urgency_level_id = :urgency_id,
                brand_id = :brand_id,
                appliance_type_id = :appliance_id,
                model_number = :model_number,
                serial_number = :serial_number,
                full_name = :full_name,
                phone_number = :phone_number,
                service_address = :service_address,
                issue_description = :issue_description
              WHERE id = :id";
    
    $stmt = $db->prepare($query);
    $result = $stmt->execute([
        ':id' => $id,
        ':status_id' => $status_id,
        ':urgency_id' => $urgency_id,
        ':brand_id' => $brand_id,
        ':appliance_id' => $appliance_id,
        ':model_number' => $model_number,
        ':serial_number' => $serial_number,
        ':full_name' => $full_name,
        ':phone_number' => $phone_number,
        ':service_address' => $service_address,
        ':issue_description' => $issue_description
    ]);
    
    if($result) {
        // If status changed, add to history
        if($current && $current['job_status_id'] != $status_id) {
            $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' => $update_notes ?: 'Status updated via admin panel',
                ':changed_by' => $_SESSION['admin_name'] ?? 'Admin'
            ]);
            
            // 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]);
            }
        }
        
        try { logRequestAction($db, $id, $_SESSION['admin_id'] ?? null, 'admin', 'request_update', $current ?: null, $_POST, $update_notes ?: 'Request updated via admin panel'); } catch (Exception $logEx) { error_log('admin update request log warning: ' . $logEx->getMessage()); }
        // Get new status info for updating the badge
        $status_query = "SELECT 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' => 'Request updated successfully',
            'new_status' => $new_status
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error updating request']);
    }
    
} catch(Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>