<?php
session_start();
include 'config.php';
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// التحقق من المصادقة
if (!isset($_SESSION['customer_id']) && !isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'error' => 'غير مصرح لك']);
    exit;
}

// تحديد نوع المستخدم
$is_customer = isset($_SESSION['customer_id']);
$is_admin = isset($_SESSION['admin_id']);
$user_id = $is_customer ? $_SESSION['customer_id'] : $_SESSION['admin_id'];
$user_name = $is_customer ? $_SESSION['customer_name'] : $_SESSION['admin_name'];

// إنشاء الجداول إذا لزم الأمر
createSupportTables($conn);

// الحصول على الإجراء
$action = $_GET['action'] ?? ($_POST['action'] ?? '');

switch ($action) {
    case 'create_ticket':
        createTicket($conn, $user_id, $user_name, $is_customer);
        break;
    case 'get_tickets':
        getTickets($conn, $user_id, $is_customer);
        break;
    case 'get_messages':
        getTicketMessages($conn, $_GET['ticket_id'] ?? 0, $user_id, $is_customer);
        break;
    case 'send_message':
        sendMessage($conn, $_POST['ticket_id'] ?? 0, $user_id, $user_name, $is_customer);
        break;
    case 'update_status':
        updateTicketStatus($conn, $_POST['ticket_id'] ?? 0, $_POST['status'] ?? '', $is_admin);
        break;
    case 'get_stats':
        getTicketStats($conn, $user_id, $is_customer);
        break;
    default:
        echo json_encode(['success' => false, 'error' => 'إجراء غير معروف']);
}

function createSupportTables($conn) {
    // إنشاء جدول التذاكر
    $conn->query("
        CREATE TABLE IF NOT EXISTS customer_tickets (
            id INT PRIMARY KEY AUTO_INCREMENT,
            customer_id INT NOT NULL,
            customer_name VARCHAR(255) NOT NULL,
            subject VARCHAR(255) NOT NULL,
            ticket_type VARCHAR(50) DEFAULT 'other',
            status ENUM('new', 'read', 'in_progress', 'resolved', 'closed') DEFAULT 'new',
            priority ENUM('low', 'medium', 'high', 'urgent') DEFAULT 'medium',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_customer (customer_id),
            INDEX idx_status (status),
            INDEX idx_priority (priority),
            INDEX idx_created (created_at)
        )
    ");
    
    // إنشاء جدول الرسائل
    $conn->query("
        CREATE TABLE IF NOT EXISTS ticket_messages (
            id INT PRIMARY KEY AUTO_INCREMENT,
            ticket_id INT NOT NULL,
            sender_type ENUM('customer', 'admin') NOT NULL,
            sender_id INT NOT NULL,
            sender_name VARCHAR(255) NOT NULL,
            message TEXT NOT NULL,
            attachments JSON,
            is_read BOOLEAN DEFAULT FALSE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (ticket_id) REFERENCES customer_tickets(id) ON DELETE CASCADE,
            INDEX idx_ticket (ticket_id),
            INDEX idx_sender (sender_type, sender_id),
            INDEX idx_read_status (is_read),
            INDEX idx_created (created_at)
        )
    ");
    
    // إنشاء جدول المرفقات
    $conn->query("
        CREATE TABLE IF NOT EXISTS ticket_attachments (
            id INT PRIMARY KEY AUTO_INCREMENT,
            ticket_id INT NOT NULL,
            message_id INT,
            file_name VARCHAR(255) NOT NULL,
            file_path VARCHAR(500) NOT NULL,
            file_type VARCHAR(50),
            file_size INT,
            uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (ticket_id) REFERENCES customer_tickets(id) ON DELETE CASCADE,
            INDEX idx_ticket (ticket_id)
        )
    ");
}

function createTicket($conn, $customer_id, $customer_name, $is_customer) {
    if (!$is_customer || $_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'error' => 'غير مصرح لك']);
        return;
    }
    
    $subject = trim($conn->real_escape_string($_POST['subject'] ?? ''));
    $ticket_type = trim($conn->real_escape_string($_POST['type'] ?? 'other'));
    $priority = trim($conn->real_escape_string($_POST['priority'] ?? 'medium'));
    $message = trim($conn->real_escape_string($_POST['message'] ?? ''));
    
    if (empty($subject) || empty($message)) {
        echo json_encode(['success' => false, 'error' => 'جميع الحقول المطلوبة']);
        return;
    }
    
    try {
        $conn->begin_transaction();
        
        // إدخال التذكرة
        $stmt = $conn->prepare("
            INSERT INTO customer_tickets (customer_id, customer_name, subject, ticket_type, priority) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->bind_param('issss', $customer_id, $customer_name, $subject, $ticket_type, $priority);
        $stmt->execute();
        $ticket_id = $conn->insert_id;
        $stmt->close();
        
        // إدخال الرسالة الأولى
        $stmt = $conn->prepare("
            INSERT INTO ticket_messages (ticket_id, sender_type, sender_id, sender_name, message) 
            VALUES (?, 'customer', ?, ?, ?)
        ");
        $stmt->bind_param('iiss', $ticket_id, $customer_id, $customer_name, $message);
        $stmt->execute();
        $message_id = $conn->insert_id;
        $stmt->close();
        
        // معالجة المرفقات
        $attachments = [];
        if (!empty($_FILES)) {
            $upload_dir = '../../admin/uploads/tickets/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            foreach ($_FILES as $key => $file) {
                if (is_array($file['name'])) {
                    // معالجة ملفات متعددة
                    for ($i = 0; $i < count($file['name']); $i++) {
                        if ($file['error'][$i] === UPLOAD_ERR_OK) {
                            $original_name = basename($file['name'][$i]);
                            $file_name = time() . '_' . $original_name;
                            $file_path = $upload_dir . $file_name;
                            
                            if (move_uploaded_file($file['tmp_name'][$i], $file_path)) {
                                // إدخال في جدول المرفقات
                                $stmt = $conn->prepare("
                                    INSERT INTO ticket_attachments (ticket_id, message_id, file_name, file_path, file_type, file_size)
                                    VALUES (?, ?, ?, ?, ?, ?)
                                ");
                                $stmt->bind_param('iisssi', $ticket_id, $message_id, $original_name, $file_path, $file['type'][$i], $file['size'][$i]);
                                $stmt->execute();
                                $stmt->close();
                                
                                $attachments[] = [
                                    'name' => $original_name,
                                    'url' => 'admin/uploads/tickets/' . $file_name,
                                    'type' => $file['type'][$i],
                                    'size' => $file['size'][$i]
                                ];
                            }
                        }
                    }
                } else {
                    // معالجة ملف واحد
                    if ($file['error'] === UPLOAD_ERR_OK) {
                        $original_name = basename($file['name']);
                        $file_name = time() . '_' . $original_name;
                        $file_path = $upload_dir . $file_name;
                        
                        if (move_uploaded_file($file['tmp_name'], $file_path)) {
                            $stmt = $conn->prepare("
                                INSERT INTO ticket_attachments (ticket_id, message_id, file_name, file_path, file_type, file_size)
                                VALUES (?, ?, ?, ?, ?, ?)
                            ");
                            $stmt->bind_param('iisssi', $ticket_id, $message_id, $original_name, $file_path, $file['type'], $file['size']);
                            $stmt->execute();
                            $stmt->close();
                            
                            $attachments[] = [
                                'name' => $original_name,
                                'url' => 'admin/uploads/tickets/' . $file_name,
                                'type' => $file['type'],
                                'size' => $file['size']
                            ];
                        }
                    }
                }
            }
            
            // تحديث الرسالة بالمرفقات
            if (!empty($attachments)) {
                $attachments_json = json_encode($attachments, JSON_UNESCAPED_UNICODE);
                $stmt = $conn->prepare("UPDATE ticket_messages SET attachments = ? WHERE id = ?");
                $stmt->bind_param('si', $attachments_json, $message_id);
                $stmt->execute();
                $stmt->close();
            }
        }
        
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'تم إرسال طلبك بنجاح. سيتم الرد عليك في أقرب وقت.',
            'ticket_id' => $ticket_id,
            'attachments' => $attachments
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        error_log("Error creating ticket: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => 'حدث خطأ في إنشاء الطلب: ' . $e->getMessage()]);
    }
}

function getTickets($conn, $user_id, $is_customer) {
    try {
        if ($is_customer) {
            // جلب تذاكر العميل
            $stmt = $conn->prepare("
                SELECT t.*, 
                       COUNT(DISTINCT m.id) as message_count,
                       MAX(CASE WHEN m.sender_type = 'admin' AND m.is_read = FALSE THEN 1 ELSE 0 END) as has_unread
                FROM customer_tickets t
                LEFT JOIN ticket_messages m ON t.id = m.ticket_id
                WHERE t.customer_id = ?
                GROUP BY t.id
                ORDER BY 
                    CASE t.status
                        WHEN 'new' THEN 1
                        WHEN 'in_progress' THEN 2
                        WHEN 'read' THEN 3
                        WHEN 'resolved' THEN 4
                        WHEN 'closed' THEN 5
                    END,
                    CASE t.priority
                        WHEN 'urgent' THEN 1
                        WHEN 'high' THEN 2
                        WHEN 'medium' THEN 3
                        WHEN 'low' THEN 4
                    END,
                    t.updated_at DESC
            ");
            $stmt->bind_param('i', $user_id);
        } else {
            // جلب جميع التذاكر للإدارة
            $stmt = $conn->prepare("
                SELECT t.*, 
                       COUNT(DISTINCT m.id) as message_count,
                       MAX(CASE WHEN m.sender_type = 'customer' AND m.is_read = FALSE THEN 1 ELSE 0 END) as has_unread
                FROM customer_tickets t
                LEFT JOIN ticket_messages m ON t.id = m.ticket_id
                GROUP BY t.id
                ORDER BY 
                    CASE t.status
                        WHEN 'new' THEN 1
                        WHEN 'in_progress' THEN 2
                        WHEN 'read' THEN 3
                        WHEN 'resolved' THEN 4
                        WHEN 'closed' THEN 5
                    END,
                    CASE t.priority
                        WHEN 'urgent' THEN 1
                        WHEN 'high' THEN 2
                        WHEN 'medium' THEN 3
                        WHEN 'low' THEN 4
                    END,
                    t.updated_at DESC
            ");
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        $tickets = [];
        
        while ($ticket = $result->fetch_assoc()) {
            // جلب أول رسالة للعرض
            $msg_stmt = $conn->prepare("
                SELECT message FROM ticket_messages 
                WHERE ticket_id = ? 
                ORDER BY created_at ASC 
                LIMIT 1
            ");
            $msg_stmt->bind_param('i', $ticket['id']);
            $msg_stmt->execute();
            $msg_result = $msg_stmt->get_result();
            $first_message = $msg_result->fetch_assoc();
            $ticket['message'] = $first_message['message'] ?? '';
            $msg_stmt->close();
            
            $tickets[] = $ticket;
        }
        $stmt->close();
        
        // حساب الرسائل غير المقروءة للعميل
        $unread_count = 0;
        if ($is_customer) {
            $unread_stmt = $conn->prepare("
                SELECT COUNT(*) as count
                FROM ticket_messages m
                JOIN customer_tickets t ON m.ticket_id = t.id
                WHERE t.customer_id = ? 
                AND m.sender_type = 'admin' 
                AND m.is_read = FALSE
            ");
            $unread_stmt->bind_param('i', $user_id);
            $unread_stmt->execute();
            $unread_result = $unread_stmt->get_result();
            $unread_row = $unread_result->fetch_assoc();
            $unread_count = $unread_row['count'] ?? 0;
            $unread_stmt->close();
        }
        
        echo json_encode([
            'success' => true,
            'tickets' => $tickets,
            'unread_count' => $unread_count
        ]);
        
    } catch (Exception $e) {
        error_log("Error getting tickets: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => 'حدث خطأ في تحميل الطلبات']);
    }
}

function getTicketMessages($conn, $ticket_id, $user_id, $is_customer) {
    if (!$ticket_id) {
        echo json_encode(['success' => false, 'error' => 'رقم الطلب غير صحيح']);
        return;
    }
    
    try {
        // التحقق من صلاحية الوصول
        if ($is_customer) {
            $check_stmt = $conn->prepare("SELECT id FROM customer_tickets WHERE id = ? AND customer_id = ?");
            $check_stmt->bind_param('ii', $ticket_id, $user_id);
        } else {
            $check_stmt = $conn->prepare("SELECT id FROM customer_tickets WHERE id = ?");
            $check_stmt->bind_param('i', $ticket_id);
        }
        
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows === 0) {
            echo json_encode(['success' => false, 'error' => 'لا يمكنك الوصول لهذا الطلب']);
            return;
        }
        
        // جلب بيانات التذكرة
        $ticket_stmt = $conn->prepare("SELECT * FROM customer_tickets WHERE id = ?");
        $ticket_stmt->bind_param('i', $ticket_id);
        $ticket_stmt->execute();
        $ticket_result = $ticket_stmt->get_result();
        $ticket = $ticket_result->fetch_assoc();
        $ticket_stmt->close();
        
        // جلب الرسائل
        $stmt = $conn->prepare("
            SELECT * FROM ticket_messages 
            WHERE ticket_id = ? 
            ORDER BY created_at ASC
        ");
        $stmt->bind_param('i', $ticket_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $messages = [];
        
        while ($message = $result->fetch_assoc()) {
            // تحليل المرفقات
            $message['attachments'] = $message['attachments'] ? json_decode($message['attachments'], true) : [];
            $messages[] = $message;
        }
        $stmt->close();
        
        // تحديث حالة الرسائل كمقروءة
        if ($is_customer) {
            $update_stmt = $conn->prepare("
                UPDATE ticket_messages 
                SET is_read = TRUE 
                WHERE ticket_id = ? 
                AND sender_type = 'admin' 
                AND is_read = FALSE
            ");
        } else {
            $update_stmt = $conn->prepare("
                UPDATE ticket_messages 
                SET is_read = TRUE 
                WHERE ticket_id = ? 
                AND sender_type = 'customer' 
                AND is_read = FALSE
            ");
        }
        $update_stmt->bind_param('i', $ticket_id);
        $update_stmt->execute();
        $update_stmt->close();
        
        echo json_encode([
            'success' => true,
            'ticket' => $ticket,
            'messages' => $messages
        ]);
        
    } catch (Exception $e) {
        error_log("Error getting messages: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => 'حدث خطأ في تحميل المحادثة']);
    }
}

function sendMessage($conn, $ticket_id, $user_id, $user_name, $is_customer) {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !$ticket_id) {
        echo json_encode(['success' => false, 'error' => 'بيانات غير صحيحة']);
        return;
    }
    
    $message = trim($conn->real_escape_string($_POST['message'] ?? ''));
    
    if (empty($message) && empty($_FILES)) {
        echo json_encode(['success' => false, 'error' => 'يجب إضافة رسالة أو صورة']);
        return;
    }
    
    try {
        $conn->begin_transaction();
        
        $sender_type = $is_customer ? 'customer' : 'admin';
        
        // إدخال الرسالة
        $stmt = $conn->prepare("
            INSERT INTO ticket_messages (ticket_id, sender_type, sender_id, sender_name, message) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->bind_param('isiss', $ticket_id, $sender_type, $user_id, $user_name, $message);
        $stmt->execute();
        $message_id = $conn->insert_id;
        $stmt->close();
        
        // تحديث وقت التذكرة
        $conn->query("UPDATE customer_tickets SET updated_at = NOW() WHERE id = $ticket_id");
        
        // تحديث حالة التذكرة
        if ($is_customer) {
            $conn->query("UPDATE customer_tickets SET status = 'new' WHERE id = $ticket_id");
        } else {
            $conn->query("UPDATE customer_tickets SET status = 'in_progress' WHERE id = $ticket_id");
        }
        
        // معالجة المرفقات
        $attachments = [];
        if (!empty($_FILES)) {
            $upload_dir = '../../admin/uploads/tickets/';
            if (!file_exists($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            foreach ($_FILES as $key => $file) {
                if (is_array($file['name'])) {
                    for ($i = 0; $i < count($file['name']); $i++) {
                        if ($file['error'][$i] === UPLOAD_ERR_OK) {
                            $original_name = basename($file['name'][$i]);
                            $file_name = time() . '_' . $original_name;
                            $file_path = $upload_dir . $file_name;
                            
                            if (move_uploaded_file($file['tmp_name'][$i], $file_path)) {
                                $stmt = $conn->prepare("
                                    INSERT INTO ticket_attachments (ticket_id, message_id, file_name, file_path, file_type, file_size)
                                    VALUES (?, ?, ?, ?, ?, ?)
                                ");
                                $stmt->bind_param('iisssi', $ticket_id, $message_id, $original_name, $file_path, $file['type'][$i], $file['size'][$i]);
                                $stmt->execute();
                                $stmt->close();
                                
                                $attachments[] = [
                                    'name' => $original_name,
                                    'url' => 'admin/uploads/tickets/' . $file_name,
                                    'type' => $file['type'][$i],
                                    'size' => $file['size'][$i]
                                ];
                            }
                        }
                    }
                } else {
                    if ($file['error'] === UPLOAD_ERR_OK) {
                        $original_name = basename($file['name']);
                        $file_name = time() . '_' . $original_name;
                        $file_path = $upload_dir . $file_name;
                        
                        if (move_uploaded_file($file['tmp_name'], $file_path)) {
                            $stmt = $conn->prepare("
                                INSERT INTO ticket_attachments (ticket_id, message_id, file_name, file_path, file_type, file_size)
                                VALUES (?, ?, ?, ?, ?, ?)
                            ");
                            $stmt->bind_param('iisssi', $ticket_id, $message_id, $original_name, $file_path, $file['type'], $file['size']);
                            $stmt->execute();
                            $stmt->close();
                            
                            $attachments[] = [
                                'name' => $original_name,
                                'url' => 'admin/uploads/tickets/' . $file_name,
                                'type' => $file['type'],
                                'size' => $file['size']
                            ];
                        }
                    }
                }
            }
            
            // تحديث الرسالة بالمرفقات
            if (!empty($attachments)) {
                $attachments_json = json_encode($attachments, JSON_UNESCAPED_UNICODE);
                $stmt = $conn->prepare("UPDATE ticket_messages SET attachments = ? WHERE id = ?");
                $stmt->bind_param('si', $attachments_json, $message_id);
                $stmt->execute();
                $stmt->close();
            }
        }
        
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'تم إرسال الرسالة بنجاح',
            'message_id' => $message_id,
            'attachments' => $attachments
        ]);
        
    } catch (Exception $e) {
        $conn->rollback();
        error_log("Error sending message: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => 'حدث خطأ في إرسال الرسالة']);
    }
}

function updateTicketStatus($conn, $ticket_id, $status, $is_admin) {
    if (!$is_admin) {
        echo json_encode(['success' => false, 'error' => 'غير مصرح لك']);
        return;
    }
    
    $allowed_statuses = ['new', 'read', 'in_progress', 'resolved', 'closed'];
    if (!in_array($status, $allowed_statuses)) {
        echo json_encode(['success' => false, 'error' => 'حالة غير صالحة']);
        return;
    }
    
    try {
        $stmt = $conn->prepare("UPDATE customer_tickets SET status = ?, updated_at = NOW() WHERE id = ?");
        $stmt->bind_param('si', $status, $ticket_id);
        $stmt->execute();
        $stmt->close();
        
        echo json_encode(['success' => true, 'message' => 'تم تحديث حالة الطلب']);
    } catch (Exception $e) {
        error_log("Error updating status: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => 'حدث خطأ في تحديث الحالة']);
    }
}

function getTicketStats($conn, $user_id, $is_customer) {
    try {
        if ($is_customer) {
            // إحصائيات العميل
            $stmt = $conn->prepare("
                SELECT 
                    COUNT(*) as total,
                    SUM(CASE WHEN status = 'new' THEN 1 ELSE 0 END) as new,
                    SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
                    SUM(CASE WHEN status = 'resolved' THEN 1 ELSE 0 END) as resolved,
                    SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed
                FROM customer_tickets 
                WHERE customer_id = ?
            ");
            $stmt->bind_param('i', $user_id);
        } else {
            // إحصائيات الإدارة
            $stmt = $conn->prepare("
                SELECT 
                    COUNT(*) as total,
                    SUM(CASE WHEN status = 'new' THEN 1 ELSE 0 END) as new,
                    SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) as in_progress,
                    SUM(CASE WHEN status = 'resolved' THEN 1 ELSE 0 END) as resolved,
                    SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END) as closed
                FROM customer_tickets
            ");
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        $stats = $result->fetch_assoc();
        $stmt->close();
        
        echo json_encode([
            'success' => true,
            'stats' => $stats
        ]);
        
    } catch (Exception $e) {
        error_log("Error getting stats: " . $e->getMessage());
        echo json_encode(['success' => false, 'error' => 'حدث خطأ في تحميل الإحصائيات']);
    }
}
?>