<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once __DIR__ . '/../../config/db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../../auth/login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];
$role = $_SESSION['role'];

// Pagination setup
$limit = 4; // Show 4 tickets per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Ticket fetch based on role
if ($role === 'admin') {
    $countStmt = $pdo->query("SELECT COUNT(*) FROM tickets");
    $total_tickets = $countStmt->fetchColumn();
    $stmt = $pdo->prepare("
        SELECT t.*, p.name AS project_name, u.full_name AS creator_name, a.full_name AS assignee_name
        FROM tickets t
        JOIN projects p ON t.project_id = p.id
        JOIN users u ON t.created_by = u.id
        LEFT JOIN users a ON t.assigned_to = a.id
        ORDER BY t.created_at DESC
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute();
} elseif ($role === 'support') {
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE assigned_to = ?");
    $countStmt->execute([$user_id]);
    $total_tickets = $countStmt->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT t.*, p.name AS project_name, u.full_name AS creator_name, a.full_name AS assignee_name
        FROM tickets t
        JOIN projects p ON t.project_id = p.id
        JOIN users u ON t.created_by = u.id
        LEFT JOIN users a ON t.assigned_to = a.id
        WHERE t.assigned_to = ?
        ORDER BY t.created_at DESC
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute([$user_id]);
} else {
    $countStmt = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE created_by = ?");
    $countStmt->execute([$user_id]);
    $total_tickets = $countStmt->fetchColumn();

    $stmt = $pdo->prepare("
        SELECT t.*, p.name AS project_name, u.full_name AS creator_name, a.full_name AS assignee_name
        FROM tickets t
        JOIN projects p ON t.project_id = p.id
        JOIN users u ON t.created_by = u.id
        LEFT JOIN users a ON t.assigned_to = a.id
        WHERE t.created_by = ?
        ORDER BY t.created_at DESC
        LIMIT $limit OFFSET $offset
    ");
    $stmt->execute([$user_id]);
}

$tickets = $stmt->fetchAll(PDO::FETCH_ASSOC);
$total_pages = ceil($total_tickets / $limit);

// Fetch comments
$commentsStmt = $pdo->prepare("
    SELECT c.*, u.full_name AS commenter
    FROM comments c
    JOIN users u ON c.user_id = u.id
    WHERE c.ticket_id = ?
    ORDER BY c.created_at ASC
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Issues - Custora CRM</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="../assets/img/custora_logo.png" type="image/png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
	:root{
	  --bg:#f4f7fa;--card-bg:rgba(173,216,230,0.35);
	  --accent:#005f8d;--muted:#666;--text:#1b2430;--white:#fff;
	}
	*{box-sizing:border-box;margin:0;padding:0;}
	body{font-family:Inter,"Segoe UI",Roboto,Arial,sans-serif;background:var(--bg);color:var(--text);}
	a{text-decoration:none;color:inherit;}
	.app{display:flex;min-height:100vh;}
	.sidebar{width:250px;background:skyblue;color:#003547;position:fixed;left:0;top:0;height:100vh;overflow:auto;z-index:100;transition:.3s;}
	.sidebar .logo{text-align:center;margin:15px 0;}
	.sidebar .logo img{width:180px;height:auto; margin-top:20px;}
	.nav{margin-top:12px;padding-left:6px;}
	.nav a{display:block;padding:10px 12px;color:#003547;border-radius:8px;margin-bottom:6px;font-weight:600;}
	.nav a:hover{background:rgba(255,255,255,0.8);box-shadow:0 2px 6px rgba(0,0,0,0.06);}
	.footer-note{text-align:center;font-size:13px;padding:10px;color:var(--muted);}
	.main{margin-left:260px;padding:20px;width:100%;transition:margin-left .25s;}
	.header{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;margin-bottom:10px;}
	.header-left{display:flex;align-items:center;gap:10px;}
	.hamburger{display:none;background:var(--accent);color:white;padding:9px 11px;border-radius:8px;cursor:pointer;}
	.title{font-weight:700;font-size:1.1rem;color:#0b66d1;}
	.controls{display:flex;align-items:center;gap:10px;}
	button#darkToggle{padding:8px 10px;border:none;border-radius:8px;background:var(--card-bg);cursor:pointer;}
	.action-btn{padding:6px 10px;border-radius:6px;margin:2px;color:white;display:inline-block;font-size:.9rem;}
	.action-edit{background:#007bff;}
	.action-delete{background:#dc3545;}
	.action-assign{background:green;}
	.status-badge{padding:4px 8px;border-radius:10px;color:white;font-size:.8rem;}
	.add{background:var(--accent);color:white;padding:10px 15px;border-radius:8px;margin-top:10px;display:inline-block;}
	.add:hover{background:#1f6391;}
	.table-wrapper{overflow-x:auto;box-shadow:0 3px 8px rgba(0,0,0,0.06);border-radius:12px;margin-top:10px;}
	table{width:100%;border-collapse:collapse;background:white;min-width:700px;}
	th,td{padding:12px 15px;text-align:left;border-bottom:1px solid #ddd;}
	th{background:var(--accent);color:white;position:sticky;top:0;z-index:2;}
	tr:hover{background:#f1f1f1;}
	.comment{background:rgba(0,95,141,0.05);padding:6px 8px;border-radius:8px;margin:4px 0;font-size:.9rem;}
	.pagination{text-align:center;margin-top:15px;}
	.pagination a{margin:0 5px;padding:8px 12px;color:#1f6391;border-radius:5px;border:1px solid #1f6391;}
	.pagination a.active{background:var(--accent); color:white;}
	.pagination a:hover{background:#1f6391; color: gold;}
	@media(max-width:768px){
	  .sidebar{transform:translateX(-280px);position:fixed;}
	  .sidebar.active{transform:translateX(0);}
	  .main{margin-left:0;padding:12px;}
	  .hamburger{display:inline-block;}
	  .actions a{display:block;width:100%;margin-bottom:4px;}
	  .add{width:100%;text-align:center;}
	}
	body.dark{--bg:#081014;--card-bg:rgba(255,255,255,0.04);--accent:#1fb6ff;--muted:#9aa6af;--text:#e6f2f6;--white:#0a0a0a;}
	body.dark .sidebar{background:linear-gradient(180deg,#0b2b33,#072024);color:#bfeafc;}
	body.dark .nav a{color:#bfeafc;}
	body.dark table{background:#071217;color:#cfeffb;}
</style>
</head>
<body>

<div class="app">
    <aside class="sidebar" id="sidebar">
        <div class="logo"><img src="../assets/img/custora_logo.png" alt="Custora CRM"></div>
        <nav class="nav">
            <a href="../"><i class="fas fa-gauge"></i> Dashboard</a>
            <?php if ($role === 'reporter'): ?>
                <a href="../projects/"><i class="fas fa-folder-open"></i> My Projects</a>
                <a href="../issues/"><i class="fas fa-bug"></i> Report Issue</a>
            <?php elseif ($role === 'support'): ?>
                <a href="../issues/"><i class="fas fa-tasks"></i> Assigned Issues</a>
                <a href="../projects/"><i class="fas fa-handshake-angle"></i> Support Projects</a>
            <?php elseif ($role === 'admin'): ?>
                <a href="../projects/"><i class="fas fa-diagram-project"></i> Manage Projects</a>
                <a href="../users/"><i class="fas fa-users-cog"></i> Manage Users</a>
                <a href="../issues/"><i class="fas fa-circle-exclamation"></i> All Issues</a>
            <?php endif; ?>
            <a href="../profile/"><i class="fas fa-user"></i> My Profile</a>
            <a href="../../auth/logout.php" style="color:#b31b1b;"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </nav>
        <div class="footer-note">&copy; <?= date('Y') ?> Digital Vortex Technologies</div>
    </aside>

    <main class="main">
        <div class="header">
            <div class="header-left">
                <div class="hamburger" id="hamburger" onclick="toggleSidebar()">☰</div>
                <div class="title">Tickets</div>
            </div>
            <div class="controls">
                <div style="font-size:0.9rem;color:var(--muted);">
                    Welcome, <strong><?= htmlspecialchars($username) ?></strong><br>
                    <small>Role: <?= htmlspecialchars($role) ?></small>
                </div>
                <button id="darkToggle"><span id="darkLabel">Dark</span></button>
            </div>
        </div>

        <a href="create.php" class="add"><i class="fas fa-plus"></i> Add Ticket</a>

        <?php if ($tickets): ?>
        <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Project</th>
                    <th>Priority</th>
                    <th>Status</th>
                    <th>Reporter</th>
                    <th>Assignee</th>
                    <th>When</th>
                    <th>Actions</th>
                    <th>Comments</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($tickets as $ticket): ?>
            <?php
                // Colored status badges
                $statusColor = match($ticket['status']) {
                    'open' => '#007bff',
                    'in_progress' => '#ffc107',
                    'on_hold' => '#6c757d',
                    'resolved' => '#28a745',
                    'closed' => '#dc3545',
                    'reopened' => '#17a2b8',
                    default => '#999'
                };
            ?>
            <tr>
                <td><?= htmlspecialchars($ticket['title']) ?></td>
                <td><?= htmlspecialchars($ticket['project_name']) ?></td>
                <?php
                    // Priority color scheme
                    $priorityColor = match(strtolower($ticket['priority'])) {
                        'urgent' => '#8b0000',    // Dark Red
                        'high'     => '#dc3545',    // Red
                        'normal'   => '#ffc107',    // Yellow
                        'low'      => '#28a745',    // Green
                        'trivial'  => '#17a2b8',    // Teal/Blue
                        default    => '#6c757d'     // Gray fallback
                    };
                ?>
                <td>
                    <span class="status-badge" style="background:<?= $priorityColor ?>;">
                        <?= ucfirst($ticket['priority']) ?>
                    </span>
                </td>

                <td><span class="status-badge" style="background:<?= $statusColor ?>;"><?= ucfirst(str_replace('_',' ',$ticket['status'])) ?></span></td>
                <td><?= htmlspecialchars($ticket['creator_name']) ?></td>
                <td><?= $ticket['assignee_name'] ? htmlspecialchars($ticket['assignee_name']) : '-' ?></td>
                <td><?= date('Y-m-d', strtotime($ticket['created_at'])) ?></td>
                <td class="actions">
                    <?php if ($ticket['status'] !== 'closed' && in_array($role, ['admin','support'])): ?>
                        <form action="close_ticket.php" method="POST" style="display:inline;">
                            <input type="hidden" name="ticket_id" value="<?= $ticket['id'] ?>">
                            <button type="submit" class="action-btn action-delete"><i class="fas fa-times-circle"></i> Close</button>
                        </form>
                    <?php elseif ($ticket['status'] === 'closed' && $role === 'admin'): ?>
                        <form action="reopen_ticket.php" method="POST" style="display:inline;">
                            <input type="hidden" name="ticket_id" value="<?= $ticket['id'] ?>">
                            <button type="submit" class="action-btn action-assign"><i class="fas fa-redo"></i> Reopen</button>
                        </form>
                    <?php else: ?>
                        <span style="color:gray;">-</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php
                        $commentsStmt->execute([$ticket['id']]);
                        $comments = $commentsStmt->fetchAll(PDO::FETCH_ASSOC);
                        if ($comments):
                            foreach ($comments as $c):
                    ?>
                        <div class="comment"><b><?= htmlspecialchars($c['commenter']) ?>:</b> <?= htmlspecialchars($c['body']) ?></div>
                    <?php endforeach; else: ?>
                        <span>No comments</span>
                    <?php endif; ?>

                    <form action="add_comment.php" method="POST" class="comment-form">
                        <input type="hidden" name="ticket_id" value="<?= $ticket['id'] ?>">
                        <textarea name="body" rows="2" placeholder="Add a comment..." required style="width:100%;border-radius:8px;padding:5px;"></textarea>
                        <button type="submit" class="action-btn action-edit" style="margin-top:6px;"><i class="fas fa-comment"></i> Post</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?> 
            <div class="pagination">
              <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <a href="?page=<?= $i ?>" class="<?= $i == $page ? 'active' : '' ?>"><?= $i ?></a>
              <?php endfor; ?>
            </div>
        <?php endif; ?>

        <?php else: ?>
            <p>No tickets available.</p>
        <?php endif; ?>
    </main>
</div>

<script>
function toggleSidebar(){
    document.getElementById('sidebar').classList.toggle('active');
}
document.addEventListener('click', function(e){
    const sidebar=document.getElementById('sidebar'),hamburger=document.getElementById('hamburger');
    if(window.innerWidth<=768 && sidebar.classList.contains('active')){
        if(!sidebar.contains(e.target)&& e.target!==hamburger){sidebar.classList.remove('active');}
    }
});
(function(){
    const body=document.body,toggle=document.getElementById('darkToggle'),label=document.getElementById('darkLabel');
    if(localStorage.getItem('custora_dark')==='1'){body.classList.add('dark');label.textContent='Light';}
    toggle.addEventListener('click',()=>{
        body.classList.toggle('dark');
        localStorage.setItem('custora_dark',body.classList.contains('dark')?'1':'0');
        label.textContent=body.classList.contains('dark')?'Light':'Dark';
    });
})();
</script>
</body>
</html>