<?php
/**
 * تذاكر الدعم الفني - للمختبرات للتواصل مع المشرف
 */
use App\Core\Auth;
use App\Core\Tenant;

require_once __DIR__ . '/../src/Core/CSRFProtection.php';

$tenantId = (int)Tenant::id();
$action = $_GET['action'] ?? 'index';

if (!($auth instanceof Auth) || !$auth->check() || !$auth->can('support_tickets.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى الدعم الفني';
    return;
}

$isSuperAdmin = ($_SESSION['tenant_id'] ?? 1) === 1 && ($_SESSION['role_id'] ?? 0) === 1;

if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Protection
    if (!\App\Core\CSRFProtection::validatePostRequest()) {
        $_SESSION['support_error'] = 'طلب غير صالح.';
        header('Location: index.php?page=support_tickets');
        exit;
    }
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');
    if (strlen($subject) >= 3 && strlen($message) >= 10) {
        try {
            $db->query('SELECT id FROM support_tickets LIMIT 1');
            $stmt = $db->prepare('INSERT INTO support_tickets (tenant_id, subject, message, status, priority, created_by) VALUES (?, ?, ?, ?, ?, ?)');
            $stmt->execute([
                $tenantId,
                $subject,
                $message,
                'open',
                $_POST['priority'] ?? 'medium',
                $_SESSION['user_id'] ?? null
            ]);
            $_SESSION['support_msg'] = 'تم إرسال التذكرة بنجاح.';
        } catch (Throwable $e) {
            $_SESSION['support_error'] = 'حدث خطأ. تأكد من تشغيل الـ migration.';
        }
    } else {
        $_SESSION['support_error'] = 'أدخل الموضوع والرسالة بشكل صحيح.';
    }
    header('Location: index.php?page=support_tickets');
    exit;
}

if ($action === 'resolve' && $isSuperAdmin && $_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Protection
    if (!\App\Core\CSRFProtection::validatePostRequest()) {
        $_SESSION['support_error'] = 'طلب غير صالح.';
        header('Location: index.php?page=support_tickets');
        exit;
    }
    $id = (int)($_POST['ticket_id'] ?? 0);
    $notes = trim($_POST['resolution_notes'] ?? '');
    if ($id > 0) {
        try {
            $db->query('SELECT id FROM support_tickets LIMIT 1');
            $stmt = $db->prepare('UPDATE support_tickets SET status = ?, resolved_at = NOW(), resolved_by = ?, resolution_notes = ? WHERE id = ?');
            $stmt->execute(['resolved', $_SESSION['user_id'] ?? null, $notes, $id]);
            $_SESSION['support_msg'] = 'تم إغلاق التذكرة.';
        } catch (Throwable $e) {}
    }
    header('Location: index.php?page=support_tickets');
    exit;
}

$tickets = [];
try {
    $db->query('SELECT id FROM support_tickets LIMIT 1');
    if ($isSuperAdmin) {
        $stmt = $db->query('SELECT st.*, t.name AS tenant_name FROM support_tickets st LEFT JOIN tenants t ON t.id = st.tenant_id ORDER BY st.id DESC LIMIT 100');
    } else {
        $stmt = $db->prepare('SELECT * FROM support_tickets WHERE tenant_id = ? ORDER BY id DESC LIMIT 50');
        $stmt->execute([$tenantId]);
    }
    $tickets = $stmt->fetchAll();
} catch (Throwable $e) {}
?>
<div class="page-header">
    <h1>تذاكر الدعم الفني</h1>
    <?php if (!$isSuperAdmin): ?>
    <button type="button" class="btn-primary" onclick="document.getElementById('newTicketForm').style.display='block'">فتح تذكرة جديدة</button>
    <?php endif; ?>
</div>

<?php if (!empty($_SESSION['support_msg'])): ?>
<div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['support_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['support_msg']); ?></div>
<?php endif; ?>
<?php if (!empty($_SESSION['support_error'])): ?>
<div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['support_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['support_error']); ?></div>
<?php endif; ?>

<div id="newTicketForm" class="section-card" style="display:none;margin-bottom:24px;">
    <h3>تذكرة جديدة</h3>
    <form method="post" action="index.php?page=support_tickets&action=create" class="form-grid">
        <div class="full-width">
            <label>الموضوع</label>
            <input type="text" name="subject" required minlength="3" placeholder="موضوع الطلب">
        </div>
        <div class="full-width">
            <label>الرسالة</label>
            <textarea name="message" rows="5" required minlength="10" placeholder="صف المشكلة أو الطلب"></textarea>
        </div>
        <div>
            <label>الأولوية</label>
            <select name="priority">
                <option value="low">منخفضة</option>
                <option value="medium" selected>متوسطة</option>
                <option value="high">عالية</option>
                <option value="urgent">عاجل</option>
            </select>
        </div>
        <div class="form-actions full-width">
            <button type="submit">إرسال التذكرة</button>
            <button type="button" class="btn-secondary" onclick="document.getElementById('newTicketForm').style.display='none'">إلغاء</button>
        </div>
    </form>
</div>

<div class="table-wrapper">
    <table class="table">
        <thead>
            <tr>
                <th>#</th>
                <?php if ($isSuperAdmin): ?><th>المختبر</th><?php endif; ?>
                <th>الموضوع</th>
                <th>الحالة</th>
                <th>التاريخ</th>
                <?php if ($isSuperAdmin): ?><th>إجراء</th><?php endif; ?>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($tickets as $t): ?>
            <tr>
                <td><?php echo (int)$t['id']; ?></td>
                <?php if ($isSuperAdmin): ?><td><?php echo htmlspecialchars($t['tenant_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td><?php endif; ?>
                <td>
                    <strong><?php echo htmlspecialchars($t['subject'], ENT_QUOTES, 'UTF-8'); ?></strong>
                    <details style="margin-top:4px;">
                        <summary style="cursor:pointer;color:var(--primary);">عرض التفاصيل</summary>
                        <p style="margin:8px 0;white-space:pre-wrap;"><?php echo htmlspecialchars($t['message'], ENT_QUOTES, 'UTF-8'); ?></p>
                        <?php if (!empty($t['resolution_notes'])): ?>
                        <p style="margin:8px 0;padding:8px;background:var(--bg-input);border-radius:6px;"><strong>رد المشرف:</strong> <?php echo nl2br(htmlspecialchars($t['resolution_notes'], ENT_QUOTES, 'UTF-8')); ?></p>
                        <?php endif; ?>
                    </details>
                </td>
                <td>
                    <?php
                    $statusLabels = ['open' => 'مفتوح', 'in_progress' => 'قيد المعالجة', 'resolved' => 'تم الحل', 'closed' => 'مغلق'];
                    echo htmlspecialchars($statusLabels[$t['status']] ?? $t['status'], ENT_QUOTES, 'UTF-8');
                    ?>
                </td>
                <td><?php echo htmlspecialchars($t['created_at'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                <?php if ($isSuperAdmin): ?>
                <td>
                    <?php if (($t['status'] ?? '') !== 'resolved' && ($t['status'] ?? '') !== 'closed'): ?>
                    <form method="post" action="index.php?page=support_tickets&action=resolve" style="display:inline;">
                        <input type="hidden" name="ticket_id" value="<?php echo (int)$t['id']; ?>">
                        <input type="text" name="resolution_notes" placeholder="رد/ملاحظة" style="width:120px;">
                        <button type="submit" class="btn-secondary btn-sm">حل</button>
                    </form>
                    <?php endif; ?>
                </td>
                <?php endif; ?>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php if (empty($tickets)): ?>
<p class="empty-state">لا توجد تذاكر.</p>
<?php endif; ?>
