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

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

$page_title = 'مدیریت تیکت‌های نمایندگان';

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

$admin_id = (int)$_SESSION['user_id'];

// پاسخ ادمین
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'reply' && $has_messages) {
    $ticket_id = (int)($_POST['ticket_id'] ?? 0);
    $message = trim($_POST['message'] ?? '');
    if ($ticket_id > 0 && $message !== '') {
        try {
            $pdo->prepare("INSERT INTO ticket_messages (ticket_id, sender_type, sender_id, message) VALUES (?, 'admin', ?, ?)")->execute([$ticket_id, $admin_id, $message]);
            $pdo->prepare("UPDATE tickets SET status = 'answered', updated_at = NOW() WHERE id = ?")->execute([$ticket_id]);
            setMessage('پاسخ ارسال شد.');
            redirect('tickets.php?view=' . $ticket_id);
        } catch (Exception $e) {
            setMessage('خطا: ' . $e->getMessage(), 'error');
        }
    }
}

// بستن تیکت
if (isset($_GET['close']) && $has_tickets) {
    $id = (int)$_GET['close'];
    try {
        $pdo->prepare("UPDATE tickets SET status = 'closed' WHERE id = ?")->execute([$id]);
        setMessage('تیکت بسته شد.');
        redirect('tickets.php');
    } catch (Exception $e) {
        setMessage('خطا: ' . $e->getMessage(), 'error');
    }
}

$view_id = isset($_GET['view']) ? (int)$_GET['view'] : 0;
$view_ticket = null;
$view_messages = [];
$rep_name = '';

if ($view_id > 0 && $has_tickets) {
    $stmt = $pdo->prepare("SELECT t.*, r.username as rep_username, r.full_name as rep_name FROM tickets t LEFT JOIN representatives r ON r.id = t.representative_id WHERE t.id = ?");
    $stmt->execute([$view_id]);
    $view_ticket = $stmt->fetch();
    if ($view_ticket) {
        $rep_name = $view_ticket['rep_name'] ?: $view_ticket['rep_username'];
        $stmt = $pdo->prepare("SELECT * FROM ticket_messages WHERE ticket_id = ? ORDER BY created_at ASC");
        $stmt->execute([$view_id]);
        $view_messages = $stmt->fetchAll();
    }
}

$tickets_list = [];
if ($has_tickets && !$view_ticket) {
    $tickets_list = $pdo->query("
        SELECT t.*, r.username as rep_username, 
               (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id = t.id) as msg_count
        FROM tickets t
        LEFT JOIN representatives r ON r.id = t.representative_id
        ORDER BY t.updated_at DESC
    ")->fetchAll();
}

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="card admin-main-card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <h3 class="card-title mb-0"><i class="bi bi-chat-dots"></i> <?= htmlspecialchars($page_title) ?></h3>
        <?php if ($view_ticket): ?>
            <a href="tickets.php" class="btn btn-outline-secondary btn-sm">بازگشت به لیست</a>
        <?php endif; ?>
    </div>
</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']) ?> — نماینده: <?= htmlspecialchars($rep_name) ?></span>
            <div>
                <span class="badge bg-<?= $view_ticket['status'] === 'closed' ? 'secondary' : 'info' ?>"><?= $view_ticket['status'] === 'closed' ? 'بسته' : 'پاسخ داده شده' ?></span>
                <?php if ($view_ticket['status'] !== 'closed'): ?>
                    <a href="?close=<?= $view_id ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('بستن این تیکت؟')">بستن تیکت</a>
                <?php endif; ?>
            </div>
        </div>
        <div class="card-body">
            <?php foreach ($view_messages as $m): ?>
                <div class="d-flex mb-3 <?= $m['sender_type'] === 'admin' ? '' : 'justify-content-end' ?>">
                    <div class="rounded p-3 <?= $m['sender_type'] === 'admin' ? 'bg-primary text-white' : 'bg-light' ?>" 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_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 admin-main-card">
        <div class="card-body">
            <?php if (empty($tickets_list)): ?>
                <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><th>عملیات</th></tr></thead>
                        <tbody>
                            <?php foreach ($tickets_list as $t): ?>
                                <tr>
                                    <td><?= htmlspecialchars($t['subject']) ?></td>
                                    <td><?= htmlspecialchars($t['rep_username'] ?? '-') ?></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 require_once '../includes/footer.php'; ?>
