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

// ============================================
// بدء الجلسة أولاً
// ============================================
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ============================================
// تضمين config.php
// ============================================
require_once __DIR__ . '/../config.php';

// ============================================
// إعدادات الـ API
// ============================================
header('Content-Type: application/json');

// ============================================
// التحقق من تسجيل الدخول
// ============================================
if (!isset($_SESSION['customer_id'])) {
    echo json_encode([
        'success' => false, 
        'message' => 'الرجاء تسجيل الدخول أولاً',
        'debug' => [
            'session_id' => session_id(),
            'session_keys' => array_keys($_SESSION),
            'cookie_name' => session_name(),
            'cookie_exists' => isset($_COOKIE[session_name()])
        ]
    ]);
    exit;
}

$customer_id = $_SESSION['customer_id'];
$customer_name = $_SESSION['customer_name'] ?? 'عميل';
$customer_phone = $_SESSION['customer_phone'] ?? '';

// ============================================
// جلب البيانات
// ============================================
$subject = trim($_POST['subject'] ?? '');
$message = trim($_POST['message'] ?? '');
$priority = $_POST['priority'] ?? 'medium';
$order_id = !empty($_POST['order_id']) ? (int)$_POST['order_id'] : null;

// التحقق من صحة البيانات
if (empty($subject)) {
    echo json_encode(['success' => false, 'message' => 'الرجاء إدخال الموضوع']);
    exit;
}

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

// ============================================
// معالجة الصورة المرفوعة
// ============================================
$image = null;
if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['attachment'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    $allowed = ['jpg', 'jpeg', 'png', 'gif'];
    if (!in_array($ext, $allowed)) {
        echo json_encode(['success' => false, 'message' => 'يسمح فقط بالصور (jpg, png, gif)']);
        exit;
    }
    
    if ($file['size'] > 2 * 1024 * 1024) {
        echo json_encode(['success' => false, 'message' => 'الصورة كبيرة جداً (الحد الأقصى 2MB)']);
        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;
    }
}

// ============================================
// إدخال البيانات في قاعدة البيانات
// ============================================
$conn->begin_transaction();

try {
    // إنشاء التذكرة
    $stmt = $conn->prepare("
        INSERT INTO support_tickets 
        (customer_id, customer_name, customer_phone, order_id, subject, priority, status, created_at) 
        VALUES (?, ?, ?, ?, ?, ?, 'pending', NOW())
    ");
    $stmt->bind_param("ississ", $customer_id, $customer_name, $customer_phone, $order_id, $subject, $priority);
    
    if (!$stmt->execute()) {
        throw new Exception("فشل في إنشاء التذكرة: " . $conn->error);
    }
    
    $ticket_id = $conn->insert_id;
    
    // إضافة رسالة العميل
    $stmt = $conn->prepare("
        INSERT INTO support_messages (ticket_id, sender_type, message, image, created_at) 
        VALUES (?, 'customer', ?, ?, NOW())
    ");
    $stmt->bind_param("iss", $ticket_id, $message, $image);
    
    if (!$stmt->execute()) {
        throw new Exception("فشل في إضافة الرسالة: " . $conn->error);
    }
    
    // الرد التلقائي
    $auto_reply = getAutoReply($message);
    if (!$auto_reply) {
        $auto_reply = "شكراً لتواصلك مع ماكس بروست. سيتم الرد على استفسارك قريباً.";
    }
    
    $stmt = $conn->prepare("
        INSERT INTO support_messages (ticket_id, sender_type, message, created_at) 
        VALUES (?, 'admin', ?, NOW())
    ");
    $stmt->bind_param("is", $ticket_id, $auto_reply);
    $stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'ticket_id' => $ticket_id,
        'message' => 'تم إرسال التذكرة بنجاح'
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    error_log("Error in send_ticket: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => 'حدث خطأ في قاعدة البيانات'
    ]);
}