<?php
require_once '../auth.php';
ensureAdminAjaxAuth();
// ajax/get_status_history.php
require_once '../../config/database.php';

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

if(!isset($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Request ID required']);
    exit;
}

$id = intval($_GET['id']);

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get request info
    $request_query = "SELECT request_number FROM service_requests WHERE id = :id";
    $request_stmt = $db->prepare($request_query);
    $request_stmt->execute([':id' => $id]);
    $request = $request_stmt->fetch(PDO::FETCH_ASSOC);
    
    if(!$request) {
        echo json_encode(['success' => false, 'message' => 'Request not found']);
        exit;
    }
    
    // Get status history
    $query = "SELECT 
                rsh.*,
                j.status_name,
                j.color_code
              FROM request_status_history rsh
              JOIN job_statuses j ON rsh.job_status_id = j.id
              WHERE rsh.request_id = :id
              ORDER BY rsh.changed_at DESC";
    
    $stmt = $db->prepare($query);
    $stmt->execute([':id' => $id]);
    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    ob_start();
    ?>
    
    <h6 class="mb-3">Request: <?php echo htmlspecialchars($request['request_number']); ?></h6>
    
    <?php if(empty($history)): ?>
        <p class="text-muted text-center py-3">No status history available</p>
    <?php else: ?>
        <div class="history-list">
            <?php foreach($history as $h): ?>
            <div class="history-item">
                <div class="d-flex justify-content-between">
                    <span class="history-status">
                        <span class="badge" style="background-color: <?php echo $h['color_code']; ?>">
                            <?php echo $h['status_name']; ?>
                        </span>
                    </span>
                    <span class="history-date">
                        <?php echo date('M d, Y h:i A', strtotime($h['changed_at'])); ?>
                    </span>
                </div>
                <?php if($h['notes']): ?>
                <div class="history-note">
                    <i class="fas fa-comment"></i>
                    <?php echo htmlspecialchars($h['notes']); ?>
                </div>
                <?php endif; ?>
                <?php if($h['changed_by']): ?>
                <div class="history-note text-muted mt-1">
                    <small>By: <?php echo htmlspecialchars($h['changed_by']); ?></small>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    
    <?php
    $html = ob_get_clean();
    
    echo json_encode([
        'success' => true,
        'html' => $html
    ]);
    
} catch(Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>