<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once '../config.php';

if (!isLoggedIn() || !isRepresentative()) {
    setMessage('دسترسی غیرمجاز', 'error');
    redirect('../login.php');
}

$page_title = 'تیکت‌های پشتیبانی';
$representative_id = (int)$_SESSION['user_id'];

try {
    $tickets_table = $pdo->query("SHOW TABLES LIKE 'tickets'")->rowCount() > 0;
    $messages_table = $pdo->query("SHOW TABLES LIKE 'ticket_messages'")->rowCount() > 0;
} catch (Exception $e) {
    $tickets_table = false;
    $messages_table = false;
}

// ارسال تیکت جدید
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create') {
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');
    if ($tickets_table && $messages_table && $subject !== '' && $message !== '') {
        try {
            $pdo->prepare("INSERT INTO tickets (representative_id, subject, status) VALUES (?, ?, 'open')")->execute([$representative_id, $subject]);
            $ticket_id = $pdo->lastInsertId();
            $pdo->prepare("INSERT INTO ticket_messages (ticket_id, sender_type, sender_id, message) VALUES (?, 'representative', ?, ?)")->execute([$ticket_id, $representative_id, $message]);
            setMessage('تیکت با موفقیت ثبت شد.');
            redirect('tickets.php');
        } catch (Exception $e) {
            setMessage('خطا: ' . $e->getMessage(), 'error');
        }
    } else {
        setMessage('موضوع و متن پیام را پر کنید', 'error');
    }
}

// پاسخ به تیکت
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reply') {
    $ticket_id = (int)($_POST['ticket_id'] ?? 0);
    $message = trim($_POST['message'] ?? '');
    if ($ticket_id > 0 && $message !== '' && $messages_table) {
        try {
            $chk = $pdo->prepare("SELECT id FROM tickets WHERE id = ? AND representative_id = ?");
            $chk->execute([$ticket_id, $representative_id]);
            if ($chk->fetch()) {
                $pdo->prepare("INSERT INTO ticket_messages (ticket_id, sender_type, sender_id, message) VALUES (?, 'representative', ?, ?)")->execute([$ticket_id, $representative_id, $message]);
                $pdo->prepare("UPDATE tickets SET status = 'open', updated_at = NOW() WHERE id = ?")->execute([$ticket_id]);
                setMessage('پاسخ شما ارسال شد.');
                redirect('tickets.php?view=' . $ticket_id);
            }
        } catch (Exception $e) {
            setMessage('خطا: ' . $e->getMessage(), 'error');
        }
    }
}

$tickets = [];
if ($tickets_table) {
    try {
        $stmt = $pdo->prepare("SELECT t.*, (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id = t.id) as msg_count FROM tickets t WHERE t.representative_id = ? ORDER BY t.updated_at DESC");
        $stmt->execute([$representative_id]);
        $tickets = $stmt->fetchAll();
    } catch (Exception $e) {
        $tickets = [];
    }
}

$view_ticket_id = isset($_GET['view']) ? (int)$_GET['view'] : 0;
$view_ticket = null;
$view_messages = [];
if ($view_ticket_id > 0 && $tickets_table && $messages_table) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM tickets WHERE id = ? AND representative_id = ?");
        $stmt->execute([$view_ticket_id, $representative_id]);
        $view_ticket = $stmt->fetch();
        if ($view_ticket) {
            $stmt = $pdo->prepare("SELECT * FROM ticket_messages WHERE ticket_id = ? ORDER BY created_at ASC");
            $stmt->execute([$view_ticket_id]);
            $view_messages = $stmt->fetchAll();
        }
    } catch (Exception $e) {}
}

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

<?php if ($msg = getMessage()): ?>
    <div class="alert alert-<?= $msg['type'] === 'error' ? 'danger' : 'success' ?> alert-dismissible fade show"><?= htmlspecialchars($msg['message']) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h5 class="mb-0"><i class="bi bi-chat-dots"></i> تیکت‌های پشتیبانی</h5>
    <?php if (!$view_ticket && $tickets_table): ?>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newTicketModal">
            <i class="bi bi-plus-lg"></i> تیکت جدید
        </button>
    <?php endif; ?>
</div>

<?php if ($view_ticket): ?>
    <div class="card mb-3">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><?= htmlspecialchars($view_ticket['subject']) ?></span>
            <div>
                <span class="badge bg-<?= $view_ticket['status'] === 'closed' ? 'secondary' : ($view_ticket['status'] === 'answered' ? 'info' : 'warning') ?>"><?= $view_ticket['status'] === 'closed' ? 'بسته' : ($view_ticket['status'] === 'answered' ? 'پاسخ داده شده' : 'باز') ?></span>
                <a href="tickets.php" class="btn btn-sm btn-outline-light">بازگشت به لیست</a>
            </div>
        </div>
        <div class="card-body">
            <?php foreach ($view_messages as $m): ?>
                <div class="d-flex mb-3 <?= $m['sender_type'] === 'representative' ? '' : 'justify-content-end' ?>">
                    <div class="rounded p-3 <?= $m['sender_type'] === 'representative' ? 'bg-light' : 'bg-primary text-white' ?>" style="max-width: 85%;">
                        <small class="d-block mb-1"><?= $m['sender_type'] === 'admin' ? 'پشتیبانی' : 'شما' ?> — <?= date('Y/m/d H:i', strtotime($m['created_at'])) ?></small>
                        <div><?= nl2br(htmlspecialchars($m['message'])) ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
            <?php if ($view_ticket['status'] !== 'closed'): ?>
                <form method="POST" class="mt-3">
                    <input type="hidden" name="action" value="reply">
                    <input type="hidden" name="ticket_id" value="<?= $view_ticket_id ?>">
                    <div class="mb-2">
                        <textarea name="message" class="form-control" rows="3" required placeholder="پاسخ خود را بنویسید..."></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">ارسال پاسخ</button>
                </form>
            <?php endif; ?>
        </div>
    </div>
<?php else: ?>
    <div class="card">
        <div class="card-body">
            <?php if (empty($tickets)): ?>
                <p class="text-muted text-center py-4 mb-0">هنوز تیکتی ثبت نکرده‌اید. با دکمه «تیکت جدید» با پشتیبانی در ارتباط باشید.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead><tr><th>موضوع</th><th>وضعیت</th><th>تعداد پیام</th><th>آخرین به‌روزرسانی</th><th>عملیات</th></tr></thead>
                        <tbody>
                            <?php foreach ($tickets as $t): ?>
                                <tr>
                                    <td><?= htmlspecialchars($t['subject']) ?></td>
                                    <td>
                                        <span class="badge bg-<?= $t['status'] === 'closed' ? 'secondary' : ($t['status'] === 'answered' ? 'info' : 'warning') ?>"><?= $t['status'] === 'closed' ? 'بسته' : ($t['status'] === 'answered' ? 'پاسخ داده شده' : 'باز') ?></span>
                                    </td>
                                    <td><?= (int)($t['msg_count'] ?? 0) ?></td>
                                    <td><?= date('Y/m/d H:i', strtotime($t['updated_at'])) ?></td>
                                    <td><a href="?view=<?= $t['id'] ?>" class="btn btn-sm btn-outline-primary">مشاهده</a></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
<?php endif; ?>

<!-- مودال تیکت جدید -->
<?php if ($tickets_table): ?>
<div class="modal fade" id="newTicketModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">تیکت جدید</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="create">
                    <div class="mb-3">
                        <label class="form-label">موضوع</label>
                        <input type="text" name="subject" class="form-control" required placeholder="موضوع تیکت">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">متن پیام</label>
                        <textarea name="message" class="form-control" rows="4" required placeholder="متن پیام خود را بنویسید..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                    <button type="submit" class="btn btn-primary">ثبت تیکت</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

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