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

require_once '../config.php';

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

if (!isset($_SESSION['customer_id'])) {
    echo json_encode(['success' => false, 'message' => 'Please login first']);
    exit;
}

$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) || empty($message)) {
    echo json_encode(['success' => false, 'message' => 'Subject and message required']);
    exit;
}

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

// 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' => 'Only images allowed']);
        exit;
    }
    
    if ($file['size'] > 2 * 1024 * 1024) {
        echo json_encode(['success' => false, 'message' => 'Image too large (max 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 {
    // Create ticket
    $stmt = $conn->prepare("
        INSERT INTO support_tickets 
        (customer_id, customer_name, customer_phone, order_id, subject, priority) 
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("ississ", $customer_id, $customer_name, $customer_phone, $order_id, $subject, $priority);
    $stmt->execute();
    
    $ticket_id = $conn->insert_id;
    
    // Insert customer message
    $stmt = $conn->prepare("
        INSERT INTO support_messages (ticket_id, sender_type, message, image) 
        VALUES (?, 'customer', ?, ?)
    ");
    $stmt->bind_param("iss", $ticket_id, $message, $image);
    $stmt->execute();
    
    // AUTO-REPLY
    $auto_reply = "شكراً لتواصلك مع ماكس برجر. سيتم الرد على استفسارك قريباً.";
    
    $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 = "نعتذر عن الخطأ. سيتم تصحيح المشكلة فوراً.";
    }
    
    $stmt = $conn->prepare("
        INSERT INTO support_messages (ticket_id, sender_type, message) 
        VALUES (?, 'admin', ?)
    ");
    $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' => 'حدث خطأ في قاعدة البيانات']);
}