<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

// Redirect to login if the admin is not authenticated
if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

// Include Database Connection
require_once "../account/include/db.php";

// --- ACTION LOGIC (Update / Delete / Create) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];

    // 1. DELETE ACTION
    if ($action === 'delete' && isset($_POST['ticket_id'])) {
        $ticket_id = (int)$_POST['ticket_id'];
        $del_q = "DELETE FROM `support_tickets` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_q)) {
            mysqli_stmt_bind_param($stmt, "i", $ticket_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Support ticket has been removed.";
                $_SESSION['swal_title'] = "Deleted";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 2. CREATE ACTION
    elseif ($action === 'add') {
        $u_id     = (int)$_POST['user_id'];
        $subject  = mysqli_real_escape_string($conn, $_POST['subject']);
        $category = mysqli_real_escape_string($conn, $_POST['category']);
        $priority = mysqli_real_escape_string($conn, $_POST['priority']);
        $message  = mysqli_real_escape_string($conn, $_POST['message']);

        $add_q = "INSERT INTO `support_tickets` (`user_id`, `subject`, `category`, `priority`, `message`, `status`, `created_at`) 
                  VALUES (?, ?, ?, ?, ?, 'open', NOW())";
        
        if ($stmt = mysqli_prepare($conn, $add_q)) {
            mysqli_stmt_bind_param($stmt, "issss", $u_id, $subject, $category, $priority, $message);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Ticket created for User ID #$u_id";
                $_SESSION['swal_title'] = "Success";
            }
            mysqli_stmt_close($stmt);
        }
    }

    // 3. EDIT ACTION
    elseif ($action === 'edit' && isset($_POST['ticket_id'])) {
        $ticket_id = (int)$_POST['ticket_id'];
        $priority  = mysqli_real_escape_string($conn, $_POST['priority']);
        $status    = mysqli_real_escape_string($conn, $_POST['status']);

        $upd_q = "UPDATE `support_tickets` SET `priority` = ?, `status` = ?, `updated_at` = NOW() WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $upd_q)) {
            mysqli_stmt_bind_param($stmt, "ssi", $priority, $status, $ticket_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "Ticket updated.";
                $_SESSION['swal_title'] = "Updated";
            }
            mysqli_stmt_close($stmt);
        }
    }

    header("Location: support_tickets.php?page=" . (isset($_GET['page']) ? (int)$_GET['page'] : 1));
    exit();
}

// --- PAGINATION & FETCH ---
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$total_res = mysqli_query($conn, "SELECT COUNT(*) as total FROM `support_tickets` ");
$total_data = mysqli_fetch_assoc($total_res);
$total_records = $total_data['total'] ?? 0;
$total_pages = ceil($total_records / $limit);

$query = "SELECT s.*, u.full_name, u.username 
          FROM `support_tickets` s 
          JOIN `users` u ON s.user_id = u.id 
          ORDER BY 
            CASE WHEN s.status = 'open' THEN 1 WHEN s.status = 'pending' THEN 2 ELSE 3 END, 
            s.created_at DESC 
          LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
    body { font-family: 'Inter', sans-serif !important; }
    .status-pill { padding: 2px 8px; border-radius: 4px; font-size: 10px; font-weight: 700; text-transform: uppercase; }
    .priority-indicator { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
    .pagination-btn { transition: all 0.2s; border: 1px solid #1e293b; color: #94a3b8; }
    .pagination-btn.active { background: #3b82f6; border-color: #3b82f6; color: white; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<main class="md:ml-64 p-4 md:p-6 min-h-[calc(100vh-65px)] bg-slate-950 relative z-10">
    
    <div class="mb-8 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
            <div class="text-[10px] font-bold text-blue-500 tracking-widest uppercase mb-1">Support Center</div>
            <h1 class="text-3xl font-bold text-white tracking-tight">Active Inquiries</h1>
        </div>
        <button onclick="ticketModal('add')" class="bg-blue-600 hover:bg-blue-500 text-white px-5 py-2.5 rounded-lg text-sm font-bold shadow-lg shadow-blue-900/20 flex items-center gap-2 transition-all">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
            Create Ticket
        </button>
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden shadow-2xl flex flex-col">
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse min-w-[1000px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4">Ticket Brief</th>
                        <th class="p-4">Applicant</th>
                        <th class="p-4">Category</th>
                        <th class="p-4 text-center">Priority</th>
                        <th class="p-4 text-center">Status</th>
                        <th class="p-4 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php if($result && mysqli_num_rows($result) > 0): ?>
                        <?php while ($row = mysqli_fetch_assoc($result)): ?>
                        <tr class="hover:bg-slate-800/30 transition-colors">
                            <td class="p-4 max-w-[300px]">
                                <div class="font-bold text-slate-100 truncate"><?php echo htmlspecialchars($row['subject'] ?? 'No Subject'); ?></div>
                                <div class="text-[10px] text-slate-500 mt-1 line-clamp-1 italic cursor-pointer" onclick='viewMessage(<?php echo json_encode($row['subject'] ?? 'Subject'); ?>, <?php echo json_encode($row['message'] ?? ''); ?>)'>
                                    <?php echo htmlspecialchars($row['message'] ?? ''); ?>
                                </div>
                            </td>
                            <td class="p-4">
                                <div class="text-slate-200 font-medium"><?php echo htmlspecialchars($row['full_name'] ?? ''); ?></div>
                                <div class="text-[10px] text-slate-500">@<?php echo htmlspecialchars($row['username'] ?? ''); ?></div>
                            </td>
                            <td class="p-4">
                                <span class="text-[11px] font-semibold text-slate-400 uppercase"><?php echo htmlspecialchars($row['category'] ?? 'General'); ?></span>
                            </td>
                            <td class="p-4 text-center">
                                <?php 
                                    $p = $row['priority'] ?? 'low';
                                    $p_color = ($p == 'high') ? 'bg-red-500' : (($p == 'medium') ? 'bg-amber-500' : 'bg-blue-500');
                                ?>
                                <span class="flex items-center justify-center gap-2 text-[10px] uppercase font-bold text-slate-400">
                                    <span class="priority-indicator <?php echo $p_color; ?>"></span>
                                    <?php echo htmlspecialchars($p); ?>
                                </span>
                            </td>
                            <td class="p-4 text-center">
                                <?php if(($row['status'] ?? '') == 'open'): ?>
                                    <span class="status-pill bg-emerald-500/10 text-emerald-500 border border-emerald-500/20">Active</span>
                                <?php elseif(($row['status'] ?? '') == 'pending'): ?>
                                    <span class="status-pill bg-amber-500/10 text-amber-500 border border-amber-500/20">Pending</span>
                                <?php else: ?>
                                    <span class="status-pill bg-slate-800 text-slate-500 border border-slate-700">Closed</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-right">
                                <div class="flex justify-end gap-3 items-center">
                                    <button onclick='viewMessage(<?php echo json_encode($row['subject'] ?? 'Inquiry'); ?>, <?php echo json_encode($row['message'] ?? ''); ?>)' class="text-slate-400 text-[10px] font-bold uppercase hover:underline">View</button>
                                    
                                    <button onclick='ticketModal("edit", <?php echo json_encode($row); ?>)' class="text-blue-500 text-[10px] font-bold uppercase hover:underline">Manage</button>
                                    
                                    <form method="POST" class="inline" onsubmit="return confirm('Permanently delete this ticket?');">
                                        <input type="hidden" name="ticket_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="submit" class="text-red-500 text-[10px] font-bold uppercase hover:underline">Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if($total_pages > 1): ?>
        <div class="p-4 border-t border-slate-800 bg-slate-900/50 flex items-center justify-between">
            <div class="text-xs text-slate-500">Page <?php echo $page; ?> of <?php echo $total_pages; ?></div>
            <div class="flex gap-1">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Prev</a>
                <?php endif; ?>
                <?php for($i = max(1, $page-1); $i <= min($total_pages, $page+1); $i++): ?>
                    <a href="?page=<?php echo $i; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs <?php echo ($i == $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="pagination-btn px-3 py-1.5 rounded text-xs">Next</a>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
// Logic to read the full message in a dedicated popup
function viewMessage(subject, message) {
    Swal.fire({
        title: subject,
        text: message,
        background: '#0f172a',
        color: '#f1f5f9',
        confirmButtonColor: '#3b82f6',
        confirmButtonText: 'Understood',
        customClass: {
            title: 'text-xl font-bold border-b border-slate-800 pb-4',
            htmlContainer: 'text-left text-slate-400 mt-4 leading-relaxed'
        }
    });
}

function ticketModal(mode, data = null) {
    let title = mode === 'add' ? 'Initiate Support Ticket' : 'Update Ticket Details';
    let btnText = mode === 'add' ? 'Create Ticket' : 'Save Changes';
    let html = '';

    if (mode === 'add') {
        html = `
            <form id="ticketForm" method="POST" class="text-left grid grid-cols-1 gap-4 mt-4">
                <input type="hidden" name="action" value="add">
                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">User ID</label>
                    <input type="number" name="user_id" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>
                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Inquiry Subject</label>
                    <input type="text" name="subject" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                </div>
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="text-[10px] uppercase font-bold text-slate-500">Category</label>
                        <select name="category" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                            <option value="General">General</option>
                            <option value="Technical">Technical</option>
                            <option value="Billing">Billing</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-[10px] uppercase font-bold text-slate-500">Priority</label>
                        <select name="priority" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                            <option value="low">Low</option>
                            <option value="medium">Medium</option>
                            <option value="high">High</option>
                        </select>
                    </div>
                </div>
                <div>
                    <label class="text-[10px] uppercase font-bold text-slate-500">Full Message</label>
                    <textarea name="message" required class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1 h-24 text-sm"></textarea>
                </div>
            </form>
        `;
    } else {
        html = `
            <form id="ticketForm" method="POST" class="text-left grid grid-cols-1 gap-4 mt-4">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="ticket_id" value="${data.id}">
                
                <div class="bg-slate-950 p-4 rounded border border-slate-800 mb-2">
                    <h4 class="text-blue-400 font-bold text-xs uppercase mb-2">Subject: ${data.subject}</h4>
                    <div class="max-h-40 overflow-y-auto text-slate-300 text-sm leading-relaxed scrollbar-thin scrollbar-thumb-slate-800">
                        ${data.message}
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="text-[10px] uppercase font-bold text-slate-500">Priority Level</label>
                        <select name="priority" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                            <option value="low" ${data.priority === 'low' ? 'selected' : ''}>Low</option>
                            <option value="medium" ${data.priority === 'medium' ? 'selected' : ''}>Medium</option>
                            <option value="high" ${data.priority === 'high' ? 'selected' : ''}>High</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-[10px] uppercase font-bold text-slate-500">Resolution Status</label>
                        <select name="status" class="w-full bg-slate-950 border border-slate-800 p-2.5 rounded text-white mt-1">
                            <option value="open" ${data.status === 'open' ? 'selected' : ''}>Open</option>
                            <option value="pending" ${data.status === 'pending' ? 'selected' : ''}>Pending</option>
                            <option value="resolved" ${data.status === 'resolved' ? 'selected' : ''}>Resolved</option>
                        </select>
                    </div>
                </div>
            </form>
        `;
    }

    Swal.fire({
        title: title,
        background: '#0f172a',
        color: '#f1f5f9',
        html: html,
        showCancelButton: true,
        confirmButtonText: btnText,
        confirmButtonColor: '#3b82f6',
        preConfirm: () => { document.getElementById('ticketForm').submit(); }
    });
}

<?php if (isset($_SESSION['swal_success'])): ?>
    Swal.fire({ title: '<?php echo $_SESSION['swal_title']; ?>', text: '<?php echo $_SESSION['swal_success']; ?>', icon: 'success', background: '#0f172a', color: '#f1f5f9', confirmButtonColor: '#3b82f6' });
    <?php unset($_SESSION['swal_success'], $_SESSION['swal_title']); ?>
<?php endif; ?>
</script>

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