<?php
// modules/tickets/tickets.php
require_once '../../includes/auth.php';
checkLogin();
require_once '../../config/db.php';
require_once '../../includes/functions.php';

// ==========================================
// فراخوانی تابع تبدیل تاریخ (حل ارور فرمت)
// ==========================================
if (!function_exists('format_shamsi')) {
    function format_shamsi($datetime) {
        if (empty($datetime)) return '-';
        $ts = strtotime($datetime);
        
        if(function_exists('gregorian_to_jalali')) {
            $jalali = gregorian_to_jalali(date('Y', $ts), date('m', $ts), date('d', $ts));
            $date_str = is_array($jalali) ? implode('/', $jalali) : $jalali;
        } else {
            $date_str = date('Y/m/d', $ts); // جایگزین امن
        }
        
        $time = date('H:i', $ts);
        return "$date_str <span class='text-[10px] text-gray-400 opacity-80'>$time</span>";
    }
}

// ==========================================
// ارتقای اتوماتیک دیتابیس (ایجاد جداول تیکت)
// ==========================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `tickets` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_id` int(11) NOT NULL,
      `subject` varchar(255) NOT NULL,
      `department` varchar(50) NOT NULL DEFAULT 'support',
      `priority` varchar(20) NOT NULL DEFAULT 'medium',
      `status` varchar(20) NOT NULL DEFAULT 'open',
      `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
      `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `ticket_messages` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `ticket_id` int(11) NOT NULL,
      `user_id` int(11) NOT NULL,
      `message` text NOT NULL,
      `attachment` varchar(255) DEFAULT NULL,
      `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
      PRIMARY KEY (`id`),
      KEY `ticket_id` (`ticket_id`),
      CONSTRAINT `fk_ticket` FOREIGN KEY (`ticket_id`) REFERENCES `tickets` (`id`) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

$userId = $_SESSION['user_id'];
$isAdmin = isAdmin();
$msg = '';
$error = '';

// ==========================================
// پردازش عملیات‌های POST (ارسال و پاسخ)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    // الف) ایجاد تیکت جدید
    if ($_POST['action'] === 'create_ticket' && !$isAdmin) {
        $subject = trim($_POST['subject']);
        $department = trim($_POST['department']);
        $priority = trim($_POST['priority']);
        $message = trim($_POST['message']);
        $attachment = null;

        if (empty($subject) || empty($message)) {
            $error = "عنوان و متن تیکت نمی‌تواند خالی باشد.";
        } else {
            if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
                $ext = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);
                $allowed = ['jpg', 'jpeg', 'png', 'pdf', 'zip', 'rar'];
                if (in_array(strtolower($ext), $allowed)) {
                    $attachment = time() . '_' . rand(100, 999) . '.' . $ext;
                    if (!is_dir('../../uploads/tickets/')) { mkdir('../../uploads/tickets/', 0777, true); }
                    move_uploaded_file($_FILES['attachment']['tmp_name'], '../../uploads/tickets/' . $attachment);
                } else {
                    $error = "فرمت فایل پیوست مجاز نیست.";
                }
            }

            if (!$error) {
                $pdo->beginTransaction();
                try {
                    $stmt = $pdo->prepare("INSERT INTO tickets (user_id, subject, department, priority, status) VALUES (?, ?, ?, ?, 'open')");
                    $stmt->execute([$userId, $subject, $department, $priority]);
                    $ticketId = $pdo->lastInsertId();

                    $stmtMsg = $pdo->prepare("INSERT INTO ticket_messages (ticket_id, user_id, message, attachment) VALUES (?, ?, ?, ?)");
                    $stmtMsg->execute([$ticketId, $userId, $message, $attachment]);

                    $pdo->commit();
                    $msg = "تیکت شما با موفقیت ثبت شد و به زودی پاسخ داده می‌شود.";
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $error = "خطا در ثبت تیکت.";
                }
            }
        }
    }

    // ب) ارسال پاسخ به تیکت
    if ($_POST['action'] === 'reply_ticket') {
        $ticketId = (int)$_POST['ticket_id'];
        $message = trim($_POST['message']);
        $attachment = null;

        $checkAccess = true;
        if (!$isAdmin) {
            $stmtCheck = $pdo->prepare("SELECT id FROM tickets WHERE id = ? AND user_id = ?");
            $stmtCheck->execute([$ticketId, $userId]);
            if (!$stmtCheck->fetch()) $checkAccess = false;
        }

        if ($checkAccess && !empty($message)) {
            if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
                $ext = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);
                $allowed = ['jpg', 'jpeg', 'png', 'pdf', 'zip', 'rar'];
                if (in_array(strtolower($ext), $allowed)) {
                    $attachment = time() . '_' . rand(100, 999) . '.' . $ext;
                    if (!is_dir('../../uploads/tickets/')) { mkdir('../../uploads/tickets/', 0777, true); }
                    move_uploaded_file($_FILES['attachment']['tmp_name'], '../../uploads/tickets/' . $attachment);
                }
            }

            $pdo->beginTransaction();
            try {
                $stmtMsg = $pdo->prepare("INSERT INTO ticket_messages (ticket_id, user_id, message, attachment) VALUES (?, ?, ?, ?)");
                $stmtMsg->execute([$ticketId, $userId, $message, $attachment]);

                $newStatus = $isAdmin ? 'answered' : 'pending';
                $pdo->prepare("UPDATE tickets SET status = ? WHERE id = ?")->execute([$newStatus, $ticketId]);

                $pdo->commit();
                $msg = "پاسخ شما با موفقیت ثبت شد.";
            } catch (Exception $e) {
                $pdo->rollBack();
                $error = "خطا در ارسال پاسخ.";
            }
        } else {
            $error = "متن پیام خالی است یا دسترسی ندارید.";
        }
    }

    // ج) تغییر وضعیت تیکت (بستن)
    if ($_POST['action'] === 'change_status' && isset($_POST['ticket_id'])) {
        $ticketId = (int)$_POST['ticket_id'];
        $newStatus = $_POST['status_val']; 
        
        $checkAccess = true;
        if (!$isAdmin) {
            $stmtCheck = $pdo->prepare("SELECT id FROM tickets WHERE id = ? AND user_id = ?");
            $stmtCheck->execute([$ticketId, $userId]);
            if (!$stmtCheck->fetch()) $checkAccess = false;
        }

        if ($checkAccess && in_array($newStatus, ['closed', 'open'])) {
            $pdo->prepare("UPDATE tickets SET status = ? WHERE id = ?")->execute([$newStatus, $ticketId]);
            $msg = "وضعیت تیکت با موفقیت تغییر کرد.";
        }
    }
}

// ==========================================
// واکشی اطلاعات و مسیریابی ویجت‌ها
// ==========================================
$viewMode = 'list'; 
$currentTicket = null;
$ticketMessages = [];

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $viewMode = 'view';
    $tId = (int)$_GET['id'];
    
    $query = "SELECT t.*, u.username, u.fullname FROM tickets t JOIN users u ON t.user_id = u.id WHERE t.id = ?";
    if (!$isAdmin) { $query .= " AND t.user_id = $userId"; }
    
    $stmt = $pdo->prepare($query);
    $stmt->execute([$tId]);
    $currentTicket = $stmt->fetch();

    if ($currentTicket) {
        $stmtMsgs = $pdo->prepare("SELECT m.*, u.username, u.fullname, u.role FROM ticket_messages m JOIN users u ON m.user_id = u.id WHERE m.ticket_id = ? ORDER BY m.created_at ASC");
        $stmtMsgs->execute([$tId]);
        $ticketMessages = $stmtMsgs->fetchAll();
    } else {
        $error = "تیکت مورد نظر یافت نشد یا شما دسترسی ندارید.";
        $viewMode = 'list';
    }
}

$adminStats = []; // آرایه برای آمار ادمین
if ($viewMode === 'list') {
    if ($isAdmin) {
        $tickets = $pdo->query("SELECT t.*, u.username, u.fullname FROM tickets t JOIN users u ON t.user_id = u.id ORDER BY FIELD(t.status, 'open', 'pending', 'answered', 'closed'), t.updated_at DESC")->fetchAll();
        
        // محاسبه آمار تیکت‌ها برای نمایش در داشبورد ادمین
        $adminStats['open'] = $pdo->query("SELECT COUNT(*) FROM tickets WHERE status = 'open'")->fetchColumn();
        $adminStats['pending'] = $pdo->query("SELECT COUNT(*) FROM tickets WHERE status = 'pending'")->fetchColumn();
        $adminStats['answered'] = $pdo->query("SELECT COUNT(*) FROM tickets WHERE status = 'answered'")->fetchColumn();
        $adminStats['closed'] = $pdo->query("SELECT COUNT(*) FROM tickets WHERE status = 'closed'")->fetchColumn();
    } else {
        $stmt = $pdo->prepare("SELECT * FROM tickets WHERE user_id = ? ORDER BY FIELD(status, 'answered', 'open', 'pending', 'closed'), updated_at DESC");
        $stmt->execute([$userId]);
        $tickets = $stmt->fetchAll();
    }
}

require_once '../../includes/header.php';
?>

<link rel="stylesheet" type="text/css" href="/vpnet-panel/assets/css/datatables.min.css">

<?php if($msg): ?><div class="bg-green-100 dark:bg-emerald-900/30 border border-green-400 dark:border-emerald-800 text-green-700 dark:text-emerald-400 px-4 py-3 rounded-xl mb-6 font-bold shadow-sm">✅ <?php echo $msg; ?></div><?php endif; ?>
<?php if($error): ?><div class="bg-red-100 dark:bg-rose-900/30 border border-red-400 dark:border-rose-800 text-red-700 dark:text-rose-400 px-4 py-3 rounded-xl mb-6 font-bold shadow-sm">❌ <?php echo $error; ?></div><?php endif; ?>

<?php 
if ($viewMode === 'view' && $currentTicket) {
    require_once 'widgets/view_ticket.php';
} else {
    require_once 'widgets/list_tickets.php';
}

require_once '../../includes/footer.php'; 
?>