<?php
/**
 * create_ticket.php - Create new support ticket
 */

require_once '../config.php';

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

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

$customer_id = $_SESSION['customer_id'];
$customer_name = $_SESSION['customer_name'] ?? '';
$customer_phone = $_SESSION['customer_phone'] ?? '';

// Get data
$subject = trim($_POST['subject'] ?? '');
$message = trim($_POST['message'] ?? '');
$order_id = !empty($_POST['order_id']) ? (int)$_POST['order_id'] : null;

if (empty($subject) || empty($message)) {
    echo json_encode(['success' => false, 'message' => 'الرجاء إدخال الموضوع والرسالة']);
    exit;
}

if (strlen($subject) < 3) {
    echo json_encode(['success' => false, 'message' => 'الموضوع قصير جداً']);
    exit;
}

if (strlen($message) < 5) {
    echo json_encode(['success' => false, 'message' => 'الرسالة قصيرة جداً']);
    exit;
}

// Verify order if provided
if ($order_id) {
    $check_order = $conn->prepare("SELECT id FROM orders WHERE id = ? AND customer_id = ?");
    $check_order->bind_param("ii", $order_id, $customer_id);
    $check_order->execute();
    if ($check_order->get_result()->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'رقم الطلب غير صحيح']);
        exit;
    }
}

// Handle attachment
$image = null;
if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['attachment'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    if (!in_array($ext, ['jpg', 'jpeg', 'png', 'gif'])) {
        echo json_encode(['success' => false, 'message' => 'يسمح فقط بالصور']);
        exit;
    }
    
    if ($file['size'] > 2 * 1024 * 1024) {
        echo json_encode(['success' => false, 'message' => 'الصورة كبيرة جداً (الحد الأقصى 2 ميجابايت)']);
        exit;
    }
    
    $upload_dir = __DIR__ . '/../../../admin7/uploads/tickets/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }
    
    $filename = time() . '_' . uniqid() . '.' . $ext;
    if (move_uploaded_file($file['tmp_name'], $upload_dir . $filename)) {
        $image = $filename;
    }
}

// Start transaction
$conn->begin_transaction();

try {
    // Create ticket
    $stmt = $conn->prepare("
        INSERT INTO support_tickets 
        (customer_id, customer_name, customer_phone, order_id, subject, priority, status, created_at) 
        VALUES (?, ?, ?, ?, ?, 'medium', 'pending', NOW())
    ");
    $stmt->bind_param("issis", $customer_id, $customer_name, $customer_phone, $order_id, $subject);
    
    if (!$stmt->execute()) {
        throw new Exception("فشل في إنشاء التذكرة");
    }
    
    $ticket_id = $conn->insert_id;
    
    // Add customer message
    $msg_stmt = $conn->prepare("
        INSERT INTO support_messages (ticket_id, sender_type, message, image, created_at) 
        VALUES (?, 'customer', ?, ?, NOW())
    ");
    $msg_stmt->bind_param("iss", $ticket_id, $message, $image);
    
    if (!$msg_stmt->execute()) {
        throw new Exception("فشل في إضافة الرسالة");
    }
    
    // Auto reply based on keywords
    $auto_reply = null;
    $lower_msg = strtolower($message);
    
    if (strpos($lower_msg, 'تأخير') !== false || strpos($lower_msg, 'delay') !== false) {
        $auto_reply = "نأسف للتأخير. جاري التحقق من حالة طلبك.";
    } elseif (strpos($lower_msg, 'خطأ') !== false || strpos($lower_msg, 'غلط') !== false) {
        $auto_reply = "نعتذر عن الخطأ. سيتم تصحيح المشكلة فوراً.";
    } elseif (strpos($lower_msg, 'استرداد') !== false || strpos($lower_msg, 'refund') !== false) {
        $auto_reply = "تم استلام طلب استرداد المبلغ. سيتم مراجعته والرد خلال 24 ساعة.";
    } elseif (strpos($lower_msg, 'شكرا') !== false || strpos($lower_msg, 'thank') !== false) {
        $auto_reply = "شكراً لتواصلك مع ماكس. خدمتك هي أولويتنا.";
    }
    
    if ($auto_reply) {
        $reply_stmt = $conn->prepare("
            INSERT INTO support_messages (ticket_id, sender_type, message, created_at) 
            VALUES (?, 'admin', ?, NOW())
        ");
        $reply_stmt->bind_param("is", $ticket_id, $auto_reply);
        $reply_stmt->execute();
    }
    
    // Create notification for admins
    $notify_message = "تذكرة جديدة #$ticket_id من $customer_name";
    $notify_stmt = $conn->prepare("
        INSERT INTO admin_notifications (title, message, type, created_at) 
        VALUES ('تذكرة جديدة', ?, 'ticket', NOW())
    ");
    $notify_stmt->bind_param("s", $notify_message);
    $notify_stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'ticket_id' => $ticket_id,
        'message' => 'تم إنشاء التذكرة بنجاح'
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    error_log("Error creating ticket: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'حدث خطأ في إنشاء التذكرة']);
}