<?php
session_start();
require_once __DIR__ . '/../config/db.php';

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

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

// Initialize counts
$totalUsers = $totalProjects = $openIssues = $assignedIssues = $myIssues = $resolvedIssues = 0;

try {
    if ($role === 'admin') {
        $totalUsers = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
        $totalProjects = (int)$pdo->query("SELECT COUNT(*) FROM projects")->fetchColumn();
        $openIssues = (int)$pdo->query("SELECT COUNT(*) FROM tickets")->fetchColumn();
    }

    if ($role === 'support') {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE assigned_to = ? AND status='new'");
        $stmt->execute([$userId]);
        $assignedIssues = (int)$stmt->fetchColumn();

        $stmt = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE assigned_to = ? AND status='resolved'");
        $stmt->execute([$userId]);
        $resolvedIssues = (int)$stmt->fetchColumn();
    }

    if ($role === 'reporter') {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE created_by = ?");
        $stmt->execute([$userId]);
        $myIssues = (int)$stmt->fetchColumn();

        $stmt = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE created_by = ? AND status='new'");
        $stmt->execute([$userId]);
        $openIssues = (int)$stmt->fetchColumn();

        $stmt = $pdo->prepare("SELECT COUNT(*) FROM tickets WHERE created_by = ? AND status='resolved'");
        $stmt->execute([$userId]);
        $resolvedIssues = (int)$stmt->fetchColumn();
    }

    $activityLogs = [];
    $stmt = $pdo->prepare("SELECT id, actor, action, target, created_at FROM activity_logs ORDER BY created_at DESC LIMIT 12");
    if ($stmt->execute()) {
        $activityLogs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    $labels = [];
    $counts = [];
    $stmt = $pdo->prepare("
        SELECT DATE(created_at) AS d, COUNT(*) AS cnt
        FROM tickets
        WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
        GROUP BY DATE(created_at)
        ORDER BY d ASC
    ");
    $dateMap = [];
    if ($stmt->execute()) {
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
            $dateMap[$r['d']] = (int)$r['cnt'];
        }
    }
    for ($i = 6; $i >= 0; $i--) {
        $d = date('Y-m-d', strtotime("-{$i} days"));
        $labels[] = date('M j', strtotime($d));
        $counts[] = $dateMap[$d] ?? 0;
    }

} catch (Exception $e) {
    $activityLogs = [];
    $labels = array_map(fn($i) => date('M j', strtotime("-$i days")), range(6, 0, -1));
    $counts = array_fill(0, 7, 0);
}

function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Custora CRM Dashboard</title>
<link rel="icon" href="assets/img/custora_logo.png" type="image/png">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://kit.fontawesome.com/a2d9b6b3c8.js" crossorigin="anonymous"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">
<style>
:root{--bg:#f4f7fa;--card-bg:rgba(173,216,230,0.35);--accent:#005f8d;--muted:#666;--text:#1b2430;--white:#fff;}
*{box-sizing:border-box;}
html,body{height:100%;margin:0;font-family:Inter, "Segoe UI", Roboto, Arial, sans-serif;background:var(--bg);color:var(--text);}
a{color:inherit;text-decoration:none;}
.app{display:flex;min-height:100vh;}
.sidebar {width:250px;background:skyblue;color:#003547;position:fixed;top:0;left:0;height:100vh;overflow:auto;transition:0.3s;z-index:100;}
.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);}
.main{margin-left:260px;padding:18px;width:100%;transition:margin-left .25s;}
.header{display:flex;align-items:center;justify-content:space-between;gap:12px;}
.header-left{display:flex;align-items:center;gap:12px;}
.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;gap:10px;align-items:center;}
.cards{margin-top:16px;display:grid;grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));gap:16px;}
.card{background:var(--card-bg);padding:18px;border-radius:12px;text-align:center;box-shadow:0 6px 18px rgba(0,0,0,0.06);transition: transform .18s ease;position:relative;}
.card:hover{transform: translateY(-6px);}
.card h3{margin:0;font-size:1rem;color:#003547;}
.card p{margin:8px 0 0;font-size:1.75rem;font-weight:700;color:#0b66d1;}
.delete-btn { margin-top:8px; background:#dc3545; color:#fff; border:none; padding:6px 10px; border-radius:6px; cursor:pointer; font-size:0.85rem; }
.grid-2{display:grid;grid-template-columns:2fr 1fr;gap:16px;margin-top:18px;}
.panel{background:linear-gradient(90deg,var(--accent),#1f6391);padding:14px;border-radius:12px;box-shadow:0 6px 18px rgba(0,0,0,0.06);}
.panel h4{margin:0 0 10px 0;font-size:1.05rem;color:white;}
.activity-list{list-style:none;padding:0;margin:0;max-height:360px;overflow:auto;}
.activity-list li{padding:10px;border-bottom:1px dashed #eee;display:flex;gap:10px;align-items:flex-start;justify-content:space-between;}
.activity-list li time{display:block;font-size:12px;color:var(--muted);}
.footer-note{margin-top:14px;font-size:13px;color:var(--muted);}
.modal { display: none; position: fixed; top:0; left:0; width:100%; height:100%; background: rgba(0,0,0,0.4); justify-content: center; align-items: center; z-index: 200; }
.modal.active { display:flex; }
.modal-content { background:white; padding:20px; border-radius:8px; max-width:400px; width:90%; text-align:center; box-shadow:0 6px 20px rgba(0,0,0,0.25); }
.modal-content h4 { margin:0 0 12px; }
.modal-buttons { margin-top:14px; display:flex; justify-content:center; gap:12px; }
.modal-buttons button { padding:8px 14px; border-radius:6px; border:none; cursor:pointer; }
.modal-buttons .cancel { background:#ccc; color:#333; }
.modal-buttons .confirm { background:#dc3545; color:white; }
@media (max-width:900px){.grid-2{grid-template-columns:1fr;}.panel{padding:12px;}}
@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;}}
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 .title{color:#072024;background:linear-gradient(90deg,#1fb6ff,#167dbf);}
body.dark .card p{color:#7ad0ff;}
body.dark .panel{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 Logo"></div>
        <nav class="nav">
            <a href="../public/"><i class="fas fa-tachometer-alt"></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-hands-helping"></i> Support Projects</a>
            <?php elseif($role==='admin'): ?>
                <a href="projects/"><i class="fas fa-project-diagram"></i> Manage Projects</a>
                <a href="users/"><i class="fas fa-users-cog"></i> Manage Users</a>
                <a href="issues/"><i class="fas fa-exclamation-circle"></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" id="main">
        <div class="header">
            <div class="header-left">
                <div class="hamburger" id="hamburger" onclick="toggleSidebar()">☰</div>
                <div class="title">Custora CRM</div>
            </div>
            <div class="controls">
                <div style="text-align:right;">
                    <div style="font-size:0.95rem;color:var(--muted)">Welcome, <strong><?= e($username) ?></strong></div>
                    <div style="font-size:0.82rem;color:var(--muted)">Role: <?= e($role) ?></div>
                </div>
                <div style="display:flex; align-items:center; gap:10px;">
                    <button id="darkToggle" title="Toggle dark mode" style="padding:8px 10px; border-radius:8px; cursor:pointer; border:none; background:var(--card-bg);">
                        <span id="darkLabel">Dark</span>
                    </button>
                </div>
            </div>
        </div>

        <section class="content panel">
            <h3 style="margin:0 0 6px 0; color:#fff;"><?= ucfirst(e($role)) ?> Dashboard</h3>
            <p style="margin:0;color:var(--white);"><?= ($role==='admin') ? 'Manage projects, users and monitor issues.' : (($role==='support') ? 'Respond to assigned tickets and support reporters.' : 'Report issues and track your tickets.'); ?></p>
        </section>

        <section class="cards" aria-live="polite" aria-atomic="true">
            <?php if($role==='admin'): ?>
                <div class="card">
                    <h3>Total Users</h3><p><?= e($totalUsers) ?></p>
                    
                </div>
                <div class="card">
                    <h3>Total Projects</h3><p><?= e($totalProjects) ?></p>
                </div>
                <div class="card">
                    <h3>Total Issues</h3><p><?= e($openIssues) ?></p>
                </div>
            <?php elseif($role==='support'): ?>
                <div class="card"><h3>Assigned Issues</h3><p><?= e($assignedIssues) ?></p><button class="delete-btn" onclick="showDeleteModal('assigned')">Delete</button></div>
                <div class="card"><h3>Resolved Issues</h3><p><?= e($resolvedIssues) ?></p><button class="delete-btn" onclick="showDeleteModal('resolved')">Delete</button></div>
            <?php else: ?>
                <div class="card"><h3>My Reported Issues</h3><p><?= e($myIssues) ?></p><button class="delete-btn" onclick="showDeleteModal('my')">Delete</button></div>
                <div class="card"><h3>Open Issues</h3><p><?= e($openIssues) ?></p><button class="delete-btn" onclick="showDeleteModal('open')">Delete</button></div>
                <div class="card"><h3>Resolved</h3><p><?= e($resolvedIssues) ?></p><button class="delete-btn" onclick="showDeleteModal('resolved_my')">Delete</button></div>
            <?php endif; ?>
        </section>

        <section class="grid-2">
            <div class="panel">
                <h4>Issues in last 7 days</h4>
                <canvas id="issuesChart" width="400" height="180"></canvas>
                <div style="margin-top:10px; font-size:13px; color:var(--muted)">Daily issues created in the last 7 days.</div>
            </div>
            <aside class="panel">
                <h4>Recent Activity</h4>
                <ul class="activity-list">
                    <?php if (!empty($activityLogs)): ?>
                        <?php foreach($activityLogs as $act): ?>
                            <li>
                                <div style="flex:1;">
                                    <strong><?= e($act['actor']) ?></strong> <?= e($act['action']) ?> <em><?= e($act['target']) ?></em>
                                    <div style="margin-top:6px;"><time><?= e(date('M j, Y H:i', strtotime($act['created_at']))) ?></time></div>
                                </div>
                                <button class="delete-btn" onclick="showDeleteModal('activity_<?= e($act['id']) ?>')"><i class="fas fa-trash-alt"></i></button>
                            </li>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <li><div>No recent activity found.</div></li>
                    <?php endif; ?>
                </ul>
            </aside>
        </section>
    </main>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal" id="deleteModal">
    <div class="modal-content">
        <h4>Delete Confirmation</h4>
        <p>This is just a placeholder. No deletion will occur.</p>
        <div class="modal-buttons">
            <button class="cancel" onclick="closeModal()">Close</button>
        </div>
    </div>
</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';}
    else{label.textContent='Dark';}
    toggle.addEventListener('click',function(){body.classList.toggle('dark');localStorage.setItem('custora_dark',body.classList.contains('dark')?'1':'0');label.textContent=body.classList.contains('dark')?'Light':'Dark';});
})();
(function(){
    const labels=<?= json_encode($labels) ?>, data=<?= json_encode($counts) ?>;
    const ctx=document.getElementById('issuesChart').getContext('2d');
    const gradient=ctx.createLinearGradient(0,0,0,200); gradient.addColorStop(0,'rgba(30,144,255,0.6)'); gradient.addColorStop(1,'rgba(30,144,255,0.05)');
    new Chart(ctx,{
        type:'line',
        data:{labels:labels,datasets:[{label:'Issues',data:data,backgroundColor:gradient,borderColor:'#1e90ff',fill:true,tension:0.25,pointRadius:4,pointBackgroundColor:'#fff',pointBorderColor:'#1e90ff'}]},
        options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false},tooltip:{mode:'index',intersect:false}},scales:{x:{grid:{display:false}},y:{beginAtZero:true,ticks:{stepSize:1}}}}
    });
})();
function showDeleteModal(id){
    document.getElementById('deleteModal').classList.add('active');
}
function closeModal(){
    document.getElementById('deleteModal').classList.remove('active');
}
</script>
</body>
</html>
