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

session_start();
require_once "config/database.php";

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') === 'guest') {
    header("Location: login.php");
    exit;
}

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$user_id = (int)($_SESSION['user_id'] ?? 0);
$full_name = trim($_SESSION['full_name'] ?? 'User');

$active_company_id = isset($_SESSION['active_company_id']) && $_SESSION['active_company_id'] !== ''
    ? (int)$_SESSION['active_company_id']
    : null;

$company_name = trim($_SESSION['company_name'] ?? '');

$selectedWorkspace = $_GET['workspace'] ?? ($_SESSION['workspace_type'] ?? 'personal');

if ($selectedWorkspace === 'company' && $active_company_id !== null) {
    $is_company_workspace = true;
    $_SESSION['workspace_type'] = 'company';
} else {
    $is_company_workspace = false;
    $selectedWorkspace = 'personal';
    $_SESSION['workspace_type'] = 'personal';
}

$currentScope = $is_company_workspace ? 'company' : 'personal';

$currentSummaryTitle = 'Dashboard';
$currentTitle = $is_company_workspace
    ? ($company_name !== '' ? $company_name . ' Document Dashboard' : 'Company Document Dashboard')
    : 'Document Dashboard';

$whereSql = $is_company_workspace
    ? "company_id = :company_id AND is_deleted = 0"
    : "user_id = :user_id AND company_id IS NULL AND is_deleted = 0";

function runCount(PDO $db, string $sql, array $params): int
{
    $stmt = $db->prepare($sql);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value[0], $value[1]);
    }
    $stmt->execute();
    return (int)$stmt->fetchColumn();
}

$params = $is_company_workspace
    ? [':company_id' => [$active_company_id, PDO::PARAM_INT]]
    : [':user_id' => [$user_id, PDO::PARAM_INT]];

$totalDocuments = runCount(
    $db,
    "SELECT COUNT(*) FROM documents WHERE {$whereSql}",
    $params
);

$expiredDocuments = runCount(
    $db,
    "SELECT COUNT(*) FROM documents 
     WHERE {$whereSql}
       AND expiry_date IS NOT NULL
       AND expiry_date <> ''
       AND expiry_date <> '0000-00-00'
       AND expiry_date < DATE_FORMAT(CURDATE(), '%Y-%m-%d')",
    $params
);

$soonDocuments = runCount(
    $db,
    "SELECT COUNT(*) FROM documents 
     WHERE {$whereSql}
       AND expiry_date IS NOT NULL
       AND expiry_date <> ''
       AND expiry_date <> '0000-00-00'
       AND expiry_date >= DATE_FORMAT(CURDATE(), '%Y-%m-%d')
       AND expiry_date <= DATE_FORMAT(DATE_ADD(CURDATE(), INTERVAL 30 DAY), '%Y-%m-%d')",
    $params
);

$noExpiryDocuments = runCount(
    $db,
    "SELECT COUNT(*) FROM documents 
     WHERE {$whereSql}
       AND (expiry_date IS NULL OR expiry_date = '' OR expiry_date = '0000-00-00')",
    $params
);

$currentStats = [
    'alerts' => $expiredDocuments + $soonDocuments,
    'documents' => [
        'total' => $totalDocuments,
        'expired' => $expiredDocuments,
        'soon' => $soonDocuments,
        'no_expiry' => $noExpiryDocuments,
    ],
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <link rel="stylesheet" href="assets/css/app.css">
</head>
<body>
<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
        <div class="page-shell">
            <section class="hero">
                <div class="hero-top">
                    <div>
                        <h1><?php echo htmlspecialchars($currentSummaryTitle); ?></h1>
                        <p>
                            <?php echo htmlspecialchars(
                                $selectedWorkspace === 'company'
                                    ? 'Overview of shared company documents and upcoming reminders.'
                                    : 'Overview of your personal documents and upcoming reminders.'
                            ); ?>
                        </p>
                    </div>

                    <div class="welcome-badge">
                        Welcome, <?php echo htmlspecialchars($full_name); ?>
                    </div>
                </div>
            </section>

            <section class="workspace-section">
                <div class="workspace-header">
                    <div class="workspace-heading">
                        <h2><?php echo htmlspecialchars($currentTitle); ?></h2>
                        <p>
                            <?php echo $selectedWorkspace === 'company'
                                ? 'Quick view of shared company documents, expiry status, and reminder activity.'
                                : 'Quick view of your personal documents, expiry status, and reminder activity.'; ?>
                        </p>
                    </div>

                    <div class="workspace-meta">
                        <?php if ((int)$currentStats['alerts'] > 0): ?>
                            <div class="alert-pill">
                                <?php echo (int)$currentStats['alerts']; ?> alert(s)
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="dashboard-grid">
                    <div class="card">
                        <div class="section-title">Documents</div>
                        <div class="section-subtext">
                            <?php echo $selectedWorkspace === 'company'
                                ? 'Quick summary of company documents.'
                                : 'Quick summary of personal documents.'; ?>
                        </div>

                        <div class="mini-grid">
                            <a class="mini-box" href="my_documents.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>">
                                <div class="mini-label">Total Documents</div>
                                <div class="mini-value"><?php echo (int)$currentStats['documents']['total']; ?></div>
                            </a>

                            <a class="mini-box" href="reminders.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>&filter=expired">
                                <div class="mini-label">Expired</div>
                                <div class="mini-value danger-text"><?php echo (int)$currentStats['documents']['expired']; ?></div>
                            </a>

                            <a class="mini-box" href="reminders.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>&filter=soon">
                                <div class="mini-label">Expiring in 30 Days</div>
                                <div class="mini-value warning-text"><?php echo (int)$currentStats['documents']['soon']; ?></div>
                            </a>

                            <a class="mini-box" href="reminders.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>&filter=no_expiry">
                                <div class="mini-label">No Expiry Date</div>
                                <div class="mini-value success-text"><?php echo (int)$currentStats['documents']['no_expiry']; ?></div>
                            </a>
                        </div>
                    </div>

                    <div class="card">
                        <div class="section-title">Reminder Overview</div>
                        <div class="section-subtext">Follow document reminders from your current workspace.</div>

                        <div class="mini-grid">
                            <a class="mini-box" href="reminders.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>">
                                <div class="mini-label">All Reminders</div>
                                <div class="mini-value"><?php echo (int)$currentStats['alerts']; ?></div>
                            </a>

                            <a class="mini-box" href="my_documents.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>">
                                <div class="mini-label">Manage Documents</div>
                                <div class="mini-value">→</div>
                            </a>

                            <a class="mini-box" href="upload_document.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>">
                                <div class="mini-label">Upload Document</div>
                                <div class="mini-value">+</div>
                            </a>

                            <a class="mini-box" href="folders.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>">
                                <div class="mini-label">Folders</div>
                                <div class="mini-value">📁</div>
                            </a>
                        </div>
                    </div>
                </div>

                <div class="quick-grid">
                    <a class="quick-card" href="my_documents.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>">
                        <div class="quick-title">My Documents</div>
                        <div class="quick-desc">View all documents, expiry dates, and reminders.</div>
                    </a>

                    <a class="quick-card" href="upload_document.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>">
                        <div class="quick-title">Upload Document</div>
                        <div class="quick-desc">Add a new document to your current workspace.</div>
                    </a>

                    <a class="quick-card" href="folders.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>">
                        <div class="quick-title">Folders</div>
                        <div class="quick-desc">Manage folders and organize uploaded files.</div>
                    </a>

                    <a class="quick-card" href="reminders.php?scope=<?php echo urlencode($currentScope); ?>&workspace=<?php echo urlencode($selectedWorkspace); ?>">
                        <div class="quick-title">Reminders</div>
                        <div class="quick-desc">Check expired and upcoming document reminders.</div>
                    </a>
                </div>
            </section>
        </div>
    </main>
</div>
</body>
</html>