<?php
/**
 * support_ajax_handler.php - معالج طلبات AJAX لنظام الدعم الفني
 */


require_once 'config.php';

// تعيين رأس JSON
header('Content-Type: application/json');

// تمكين عرض الأخطاء للتشخيص
error_reporting(E_ALL);
ini_set('display_errors', 1);

// دالة مساعدة لإرجاع الردود
function jsonResponse($success, $message, $data = null) {
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

// التحقق من وجود الإجراء المطلوب
if (!isset($_POST['action'])) {
    jsonResponse(false, 'الإجراء غير محدد');
}

$action = $_POST['action'];

// اختبار الاتصال
if ($action === 'test') {
    jsonResponse(true, 'الاتصال ناجح', ['timestamp' => date('Y-m-d H:i:s')]);
}

// ==========================================
// 1. إرسال تذكرة جديدة (من صفحة العميل)
// ==========================================
if ($action === 'send_ticket') {
    // التحقق من تسجيل دخول العميل
    if (!isset($_SESSION['customer_id'])) {
        jsonResponse(false, 'يجب تسجيل الدخول أولاً');
    }
    
    $customer_id = $_SESSION['customer_id'];
    $customer_name = $_SESSION['customer_name'] ?? null;
    $customer_phone = $_SESSION['customer_phone'] ?? null;
    
    // جلب بيانات العميل إذا لم تكن موجودة في الجلسة
    if (!$customer_name || !$customer_phone) {
        $stmt = $conn->prepare("SELECT name, phone FROM customers WHERE id = ?");
        $stmt->bind_param("i", $customer_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $customer = $result->fetch_assoc();
        if ($customer) {
            $customer_name = $customer['name'];
            $customer_phone = $customer['phone'];
        }
        $stmt->close();
    }
    
    // التحقق من البيانات المطلوبة
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');
    $order_id = !empty($_POST['order_id']) ? (int)$_POST['order_id'] : null;
    $priority = $_POST['priority'] ?? 'medium';
    
    if (empty($subject)) {
        jsonResponse(false, 'الموضوع مطلوب');
    }
    
    if (empty($message)) {
        jsonResponse(false, 'الرسالة مطلوبة');
    }
    
    // التحقق من الأولوية
    $allowed_priorities = ['low', 'medium', 'high'];
    if (!in_array($priority, $allowed_priorities)) {
        $priority = 'medium';
    }
    
    // إنشاء التذكرة
    $stmt = $conn->prepare("
        INSERT INTO support_tickets (customer_id, customer_name, customer_phone, order_id, subject, priority, status, created_at, updated_at) 
        VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW(), NOW())
    ");
    $stmt->bind_param("ississ", $customer_id, $customer_name, $customer_phone, $order_id, $subject, $priority);
    
    if (!$stmt->execute()) {
        jsonResponse(false, 'حدث خطأ في إنشاء التذكرة: ' . $conn->error);
    }
    
    $ticket_id = $stmt->insert_id;
    $stmt->close();
    
    // معالجة المرفق إن وجد
    $attachment_path = null;
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = dirname(__DIR__) . '/uploads/tickets/';
        
        // إنشاء المجلد إذا لم يكن موجوداً
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $file_ext = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);
        $allowed_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (in_array(strtolower($file_ext), $allowed_ext)) {
            $file_name = 'ticket_' . $ticket_id . '_' . time() . '.' . $file_ext;
            $file_path = $upload_dir . $file_name;
            
            if (move_uploaded_file($_FILES['attachment']['tmp_name'], $file_path)) {
                $attachment_path = $file_name;
            }
        }
    }
    
    // إضافة الرسالة الأولى
    $stmt = $conn->prepare("
        INSERT INTO support_messages (ticket_id, sender_type, message, image, is_read, created_at) 
        VALUES (?, 'customer', ?, ?, 1, NOW())
    ");
    $stmt->bind_param("iss", $ticket_id, $message, $attachment_path);
    
    if (!$stmt->execute()) {
        $conn->query("DELETE FROM support_tickets WHERE id = $ticket_id");
        jsonResponse(false, 'حدث خطأ في إضافة الرسالة: ' . $conn->error);
    }
    
    $stmt->close();
    
    jsonResponse(true, 'تم إرسال التذكرة بنجاح', ['ticket_id' => $ticket_id]);
}

// ==========================================
// 2. جلب رسائل التذكرة (من صفحة العميل)
// ==========================================
if ($action === 'fetch_messages') {
    // التحقق من تسجيل دخول العميل
    if (!isset($_SESSION['customer_id'])) {
        jsonResponse(false, 'يجب تسجيل الدخول أولاً');
    }
    
    $ticket_id = (int)$_POST['ticket_id'];
    $last_id = (int)($_POST['last_id'] ?? 0);
    $customer_id = $_SESSION['customer_id'];
    
    // التحقق من أن التذكرة تخص هذا العميل
    $stmt = $conn->prepare("SELECT id, subject, status, priority FROM support_tickets WHERE id = ? AND customer_id = ?");
    $stmt->bind_param("ii", $ticket_id, $customer_id);
    $stmt->execute();
    $ticket_result = $stmt->get_result();
    $ticket = $ticket_result->fetch_assoc();
    $stmt->close();
    
    if (!$ticket) {
        jsonResponse(false, 'التذكرة غير موجودة أو لا تخصك');
    }
    
    // تحديث حالة القراءة للرسائل الجديدة من الإدارة
    $stmt = $conn->prepare("
        UPDATE support_messages 
        SET is_read = 1 
        WHERE ticket_id = ? AND sender_type = 'admin' AND is_read = 0
    ");
    $stmt->bind_param("i", $ticket_id);
    $stmt->execute();
    $stmt->close();
    
    // جلب الرسائل
    $query = "SELECT id, sender_type as sender, message, image as attachment, 
              DATE_FORMAT(created_at, '%H:%i') as time,
              DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') as full_time
              FROM support_messages 
              WHERE ticket_id = $ticket_id 
              ORDER BY created_at ASC";
    
    $messages_result = $conn->query($query);
    
    $messages = [];
    if ($messages_result && $messages_result->num_rows > 0) {
        while ($msg = $messages_result->fetch_assoc()) {
            if (!empty($msg['attachment'])) {
                $msg['attachment'] = '../uploads/tickets/' . $msg['attachment'];
            }
            $messages[] = $msg;
        }
    }
    
    jsonResponse(true, 'تم جلب الرسائل', [
        'messages' => $messages,
        'ticket' => [
            'id' => $ticket['id'],
            'subject' => $ticket['subject'],
            'status' => $ticket['status'],
            'priority' => $ticket['priority']
        ]
    ]);
}

// ==========================================
// 3. إرسال رسالة جديدة (من صفحة العميل)
// ==========================================
if ($action === 'send_message') {
    // التحقق من تسجيل دخول العميل
    if (!isset($_SESSION['customer_id'])) {
        jsonResponse(false, 'يجب تسجيل الدخول أولاً');
    }
    
    $ticket_id = (int)$_POST['ticket_id'];
    $message = trim($_POST['message'] ?? '');
    $customer_id = $_SESSION['customer_id'];
    
    if (empty($message)) {
        jsonResponse(false, 'الرسالة مطلوبة');
    }
    
    // التحقق من أن التذكرة تخص هذا العميل
    $stmt = $conn->prepare("SELECT status FROM support_tickets WHERE id = ? AND customer_id = ?");
    $stmt->bind_param("ii", $ticket_id, $customer_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $ticket = $result->fetch_assoc();
    $stmt->close();
    
    if (!$ticket) {
        jsonResponse(false, 'التذكرة غير موجودة أو لا تخصك');
    }
    
    if ($ticket['status'] === 'resolved') {
        jsonResponse(false, 'لا يمكن إرسال رسائل لتذكرة مغلقة');
    }
    
    // معالجة المرفق
    $attachment_path = null;
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = dirname(__DIR__) . '/uploads/tickets/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $file_ext = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);
        $allowed_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (in_array(strtolower($file_ext), $allowed_ext)) {
            $file_name = 'msg_' . $ticket_id . '_' . time() . '.' . $file_ext;
            if (move_uploaded_file($_FILES['attachment']['tmp_name'], $upload_dir . $file_name)) {
                $attachment_path = $file_name;
            }
        }
    }
    
    // إضافة الرسالة
    $stmt = $conn->prepare("
        INSERT INTO support_messages (ticket_id, sender_type, message, image, is_read, created_at) 
        VALUES (?, 'customer', ?, ?, 1, NOW())
    ");
    $stmt->bind_param("iss", $ticket_id, $message, $attachment_path);
    
    if (!$stmt->execute()) {
        jsonResponse(false, 'حدث خطأ في إرسال الرسالة: ' . $conn->error);
    }
    $stmt->close();
    
    // تحديث حالة التذكرة
    $stmt = $conn->prepare("
        UPDATE support_tickets 
        SET status = 'in_progress', updated_at = NOW() 
        WHERE id = ? AND status = 'pending'
    ");
    $stmt->bind_param("i", $ticket_id);
    $stmt->execute();
    $stmt->close();
    
    jsonResponse(true, 'تم إرسال الرسالة');
}

// ==========================================
// 4. إرسال رد من المسؤول
// ==========================================
if ($action === 'send_admin_reply') {
    if (!isset($_SESSION['admin_id'])) {
        jsonResponse(false, 'غير مصرح لك');
    }
    
    $ticket_id = (int)$_POST['ticket_id'];
    $message = trim($_POST['message'] ?? '');
    
    if (empty($message)) {
        jsonResponse(false, 'الرسالة مطلوبة');
    }
    
    $stmt = $conn->prepare("SELECT status FROM support_tickets WHERE id = ?");
    $stmt->bind_param("i", $ticket_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $ticket = $result->fetch_assoc();
    $stmt->close();
    
    if (!$ticket) {
        jsonResponse(false, 'التذكرة غير موجودة');
    }
    
    if ($ticket['status'] === 'resolved') {
        jsonResponse(false, 'لا يمكن الرد على تذكرة مغلقة');
    }
    
    // معالجة المرفق
    $attachment_path = null;
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = dirname(__DIR__) . '../../../admin7/uploads/tickets/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $file_ext = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);
        $allowed_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (in_array(strtolower($file_ext), $allowed_ext)) {
            $file_name = 'admin_' . $ticket_id . '_' . time() . '.' . $file_ext;
            if (move_uploaded_file($_FILES['attachment']['tmp_name'], $upload_dir . $file_name)) {
                $attachment_path = $file_name;
            }
        }
    }
    
    // إضافة الرسالة (is_read = 0 لأنها غير مقروءة من العميل)
    $stmt = $conn->prepare("
        INSERT INTO support_messages (ticket_id, sender_type, message, image, is_read, created_at) 
        VALUES (?, 'admin', ?, ?, 0, NOW())
    ");
    $stmt->bind_param("iss", $ticket_id, $message, $attachment_path);
    
    if (!$stmt->execute()) {
        jsonResponse(false, 'حدث خطأ في إرسال الرد: ' . $conn->error);
    }
    $stmt->close();
    
    // تحديث حالة التذكرة
    $stmt = $conn->prepare("
        UPDATE support_tickets 
        SET status = 'in_progress', updated_at = NOW() 
        WHERE id = ? AND status = 'pending'
    ");
    $stmt->bind_param("i", $ticket_id);
    $stmt->execute();
    $stmt->close();
    
    jsonResponse(true, 'تم إرسال الرد');
}

// ==========================================
// 5. جلب رسائل التذكرة للمسؤول
// ==========================================
if ($action === 'fetch_admin_messages') {
    if (!isset($_SESSION['admin_id'])) {
        jsonResponse(false, 'غير مصرح لك');
    }
    
    $ticket_id = (int)$_POST['ticket_id'];
    
    $stmt = $conn->prepare("SELECT id, subject, status, priority FROM support_tickets WHERE id = ?");
    $stmt->bind_param("i", $ticket_id);
    $stmt->execute();
    $ticket_result = $stmt->get_result();
    $ticket = $ticket_result->fetch_assoc();
    $stmt->close();
    
    if (!$ticket) {
        jsonResponse(false, 'التذكرة غير موجودة');
    }
    
    // تحديث حالة القراءة لرسائل العملاء
    $stmt = $conn->prepare("
        UPDATE support_messages 
        SET is_read = 1 
        WHERE ticket_id = ? AND sender_type = 'customer' AND is_read = 0
    ");
    $stmt->bind_param("i", $ticket_id);
    $stmt->execute();
    $stmt->close();
    
    // جلب جميع الرسائل
    $query = "SELECT id, sender_type as sender, message, image as attachment, 
              DATE_FORMAT(created_at, '%H:%i') as time,
              DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s') as full_time
              FROM support_messages 
              WHERE ticket_id = $ticket_id 
              ORDER BY created_at ASC";
    
    $messages_result = $conn->query($query);
    
    $messages = [];
    if ($messages_result && $messages_result->num_rows > 0) {
        while ($msg = $messages_result->fetch_assoc()) {
            if (!empty($msg['attachment'])) {
                $msg['attachment'] = '../../admin7/uploads/tickets/' . $msg['attachment'];
            }
            $messages[] = $msg;
        }
    }
    
    jsonResponse(true, 'تم جلب الرسائل', [
        'messages' => $messages,
        'ticket' => [
            'id' => $ticket['id'],
            'subject' => $ticket['subject'],
            'status' => $ticket['status'],
            'priority' => $ticket['priority']
        ]
    ]);
}

// ==========================================
// 6. تحديث حالة التذكرة
// ==========================================
if ($action === 'update_status') {
    if (!isset($_SESSION['admin_id'])) {
        jsonResponse(false, 'غير مصرح لك');
    }
    
    $ticket_id = (int)$_POST['ticket_id'];
    $status = $_POST['status'] ?? '';
    
    $allowed_statuses = ['pending', 'in_progress', 'resolved'];
    if (!in_array($status, $allowed_statuses)) {
        jsonResponse(false, 'حالة غير صالحة');
    }
    
    $stmt = $conn->prepare("UPDATE support_tickets SET status = ?, updated_at = NOW() WHERE id = ?");
    $stmt->bind_param("si", $status, $ticket_id);
    
    if (!$stmt->execute()) {
        jsonResponse(false, 'حدث خطأ في تحديث الحالة');
    }
    $stmt->close();
    
    if ($status === 'resolved') {
        $message = "تم إغلاق التذكرة. شكراً لتواصلك مع ماكس بروست.";
        $stmt = $conn->prepare("
            INSERT INTO support_messages (ticket_id, sender_type, message, is_read, created_at) 
            VALUES (?, 'system', ?, 1, NOW())
        ");
        $stmt->bind_param("is", $ticket_id, $message);
        $stmt->execute();
        $stmt->close();
    }
    
    jsonResponse(true, 'تم تحديث الحالة بنجاح', ['status' => $status]);
}

// ==========================================
// 7. جلب قائمة التذاكر للمسؤول
// ==========================================
if ($action === 'fetch_tickets_list') {
    if (!isset($_SESSION['admin_id'])) {
        jsonResponse(false, 'غير مصرح لك');
    }
    
    $status_filter = $_POST['status'] ?? 'all';
    $priority_filter = $_POST['priority'] ?? 'all';
    $search_filter = trim($_POST['search'] ?? '');
    
    $where = "1=1";
    $params = [];
    $types = "";
    
    if ($status_filter != 'all') {
        $where .= " AND status = ?";
        $params[] = $status_filter;
        $types .= "s";
    }
    
    if ($priority_filter != 'all') {
        $where .= " AND priority = ?";
        $params[] = $priority_filter;
        $types .= "s";
    }
    
    if (!empty($search_filter)) {
        $where .= " AND (subject LIKE ? OR customer_name LIKE ? OR customer_phone LIKE ?)";
        $search = "%$search_filter%";
        $params[] = $search;
        $params[] = $search;
        $params[] = $search;
        $types .= "sss";
    }
    
    $query = "
        SELECT 
            t.*,
            (SELECT COUNT(*) FROM support_messages WHERE ticket_id = t.id AND is_read = 0 AND sender_type = 'customer') as unread,
            (SELECT message FROM support_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_message
        FROM support_tickets t
        WHERE $where
        ORDER BY 
            CASE t.status
                WHEN 'pending' THEN 1
                WHEN 'in_progress' THEN 2
                WHEN 'resolved' THEN 3
                ELSE 4
            END,
            CASE t.priority
                WHEN 'high' THEN 1
                WHEN 'medium' THEN 2
                WHEN 'low' THEN 3
                ELSE 4
            END,
            t.created_at DESC
        LIMIT 100
    ";
    
    $stmt = $conn->prepare($query);
    if (!empty($params)) {
        $stmt->bind_param($types, ...$params);
    }
    $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;
    }
    $stmt->close();
    
    jsonResponse(true, 'تم جلب التذاكر', ['tickets' => $tickets]);
}

// ==========================================
// 8. جلب إحصائيات التذاكر
// ==========================================
if ($action === 'fetch_stats') {
    if (!isset($_SESSION['admin_id'])) {
        jsonResponse(false, 'غير مصرح لك');
    }
    
    $total_result = $conn->query("SELECT COUNT(*) as total FROM support_tickets");
    $total = $total_result ? $total_result->fetch_assoc()['total'] : 0;
    
    $pending_result = $conn->query("SELECT COUNT(*) as pending FROM support_tickets WHERE status = 'pending'");
    $pending = $pending_result ? $pending_result->fetch_assoc()['pending'] : 0;
    
    $progress_result = $conn->query("SELECT COUNT(*) as in_progress FROM support_tickets WHERE status = 'in_progress'");
    $in_progress = $progress_result ? $progress_result->fetch_assoc()['in_progress'] : 0;
    
    $resolved_result = $conn->query("SELECT COUNT(*) as resolved FROM support_tickets WHERE status = 'resolved'");
    $resolved = $resolved_result ? $resolved_result->fetch_assoc()['resolved'] : 0;
    
    $high_result = $conn->query("SELECT COUNT(*) as high_count FROM support_tickets WHERE priority = 'high'");
    $high_priority = $high_result ? $high_result->fetch_assoc()['high_count'] : 0;
    
    jsonResponse(true, 'تم جلب الإحصائيات', [
        'stats' => [
            'total' => $total,
            'pending' => $pending,
            'in_progress' => $in_progress,
            'resolved' => $resolved,
            'high_priority' => $high_priority
        ]
    ]);
}

// ==========================================
// إذا لم يتم العثور على الإجراء
// ==========================================
jsonResponse(false, 'إجراء غير معروف: ' . $action);
?>