<?php
/**
 * get_tickets.php - Get customer tickets
 */

require_once '../config.php';

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

if (!isset($_SESSION['customer_id'])) {
    echo json_encode(['success' => false, 'message' => 'الرجاء تسجيل الدخول أولاً']);
    exit;
}

$customer_id = $_SESSION['customer_id'];

// Get tickets with last message and unread count
$stmt = $conn->prepare("
    SELECT 
        t.*,
        (SELECT message FROM support_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_message,
        (SELECT created_at FROM support_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_message_time,
        (SELECT COUNT(*) FROM support_messages WHERE ticket_id = t.id AND sender_type = 'admin' AND is_read = 0) as unread_count
    FROM support_tickets t
    WHERE t.customer_id = ?
    ORDER BY 
        CASE t.status
            WHEN 'pending' THEN 1
            WHEN 'in_progress' THEN 2
            WHEN 'resolved' THEN 3
        END,
        t.created_at DESC
");

$stmt->bind_param("i", $customer_id);
$stmt->execute();
$result = $stmt->get_result();

$tickets = [];
while ($row = $result->fetch_assoc()) {
    $row['status_text'] = [
        'pending' => 'قيد الانتظار',
        'in_progress' => 'قيد المعالجة',
        'resolved' => 'تم الحل'
    ][$row['status']];
    
    $row['priority_text'] = [
        'low' => 'منخفضة',
        'medium' => 'متوسطة',
        'high' => 'عالية'
    ][$row['priority']];
    
    $tickets[] = $row;
}

echo json_encode([
    'success' => true,
    'tickets' => $tickets,
    'count' => count($tickets)
]);