<?php
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);
$search = trim($_GET['search'] ?? '');
$category = trim($_GET['category'] ?? '');

$reminder = trim($_GET['reminder'] ?? '');

$requested_company_id = (int)($_GET['company_id'] ?? 0);

$workspace = $_GET['workspace'] ?? 'personal';
$scope = $_GET['scope'] ?? $workspace;

$all_workspace_company_id = null;
$is_all_workspace = ($workspace === 'all');
if ($is_all_workspace && $requested_company_id > 0) {
    $stmtAllCompany = $db->prepare("
        SELECT c.id, c.company_name
        FROM company_users cu
        INNER JOIN companies c ON c.id = cu.company_id
        WHERE cu.user_id = :user_id
          AND cu.company_id = :company_id
        LIMIT 1
    ");
    $stmtAllCompany->bindValue(':user_id', $user_id, PDO::PARAM_INT);
    $stmtAllCompany->bindValue(':company_id', $requested_company_id, PDO::PARAM_INT);
    $stmtAllCompany->execute();

    $allCompanyRow = $stmtAllCompany->fetch(PDO::FETCH_ASSOC);

    if ($allCompanyRow) {
        $all_workspace_company_id = (int)$allCompanyRow['id'];
        $company_name = trim((string)($allCompanyRow['company_name'] ?? ''));
    }
}


$all_workspace_company_id = ($workspace === 'all' && $requested_company_id > 0)
    ? $requested_company_id
    : null;







$active_company_id = null;
$company_name = '';
$is_company_workspace = false;

if ($workspace === 'company' && $requested_company_id > 0) {
    $stmtCompany = $db->prepare("
        SELECT c.id, c.company_name
        FROM company_users cu
        INNER JOIN companies c ON c.id = cu.company_id
        WHERE cu.user_id = :user_id
          AND cu.company_id = :company_id
        LIMIT 1
    ");
    $stmtCompany->bindValue(':user_id', $user_id, PDO::PARAM_INT);
    $stmtCompany->bindValue(':company_id', $requested_company_id, PDO::PARAM_INT);
    $stmtCompany->execute();

    $companyRow = $stmtCompany->fetch(PDO::FETCH_ASSOC);

    if ($companyRow) {
        $is_company_workspace = true;
        $active_company_id = (int)$companyRow['id'];
        $company_name = trim((string)($companyRow['company_name'] ?? ''));
        $_SESSION['workspace_type'] = 'company';
    } else {
        $_SESSION['workspace_type'] = 'personal';
    }
} else {
    $_SESSION['workspace_type'] = 'personal';
}

if ($is_all_workspace) {
    $scope = 'all';
} elseif ($is_company_workspace) {
    $scope = 'company';
} else {
    $scope = 'personal';
}

if ($is_all_workspace) {
    $workspace_label = !empty($all_workspace_company_id) && $company_name !== ''
        ? 'All Workspaces • ' . $company_name
        : 'All Workspaces';
} elseif ($is_company_workspace) {
    $workspace_label = $company_name !== ''
        ? $company_name . ' (Company Workspace)'
        : 'Company Workspace';
} else {
    $workspace_label = 'Personal Workspace';
}

function formatDateForDisplay(?string $date): string
{
    $date = trim((string)$date);

    if ($date === '') {
        return '-';
    }

    $dt = DateTime::createFromFormat('Y-m-d', $date);
    if ($dt) {
        return $dt->format('d/m/Y');
    }

    return $date;
}

function getReminderMonths(?string $category): int
{
    $category = strtolower(trim((string)$category));

    if ($category === 'passport') {
        return 10;
    }

    return 3;
}

function getReminderDate(?string $expiryDate, ?string $category): ?DateTime
{
    $expiryDate = trim((string)$expiryDate);

    if ($expiryDate === '') {
        return null;
    }

    $dt = DateTime::createFromFormat('Y-m-d', $expiryDate);
    if (!$dt) {
        return null;
    }

    $months = getReminderMonths($category);
    $dt->modify("-{$months} months");

    return $dt;
}

function getReminderStatus(?string $expiryDate, ?string $category): string
{
    $reminderDate = getReminderDate($expiryDate, $category);

    if (!$reminderDate) {
        return '-';
    }

    $today = new DateTime('today');

    if ($today >= $reminderDate) {
        return 'Remind now';
    }

    return 'Waiting';
}

function getDaysLeft(?string $expiryDate): ?int
{
    $expiryDate = trim((string)$expiryDate);

    if ($expiryDate === '') {
        return null;
    }

    $expiry = DateTime::createFromFormat('Y-m-d', $expiryDate);
    if (!$expiry) {
        return null;
    }

    $today = new DateTime('today');
    $interval = $today->diff($expiry);

    if ($expiry < $today) {
        return -((int)$interval->days);
    }

    return (int)$interval->days;
}

function formatDaysLeft(?string $expiryDate): string
{
    $daysLeft = getDaysLeft($expiryDate);

    if ($daysLeft === null) {
        return '-';
    }

    if ($daysLeft < 0) {
        return 'Expired ' . abs($daysLeft) . ' day(s) ago';
    }

    if ($daysLeft === 0) {
        return 'Expires today';
    }

    return $daysLeft . ' day(s)';
}

function getDaysLeftClass(?string $expiryDate): string
{
    $daysLeft = getDaysLeft($expiryDate);

    if ($daysLeft === null) {
        return 'days-muted';
    }

    if ($daysLeft < 0) {
        return 'days-expired';
    }

    if ($daysLeft <= 60) {
        return 'days-danger';
    }

    if ($daysLeft <= 90) {
        return 'days-warning';
    }

    return 'days-safe';
}

function workspaceQueryString(string $scope, ?int $companyId = null, array $extra = []): string
{
    $params = array_merge([
        'workspace' => $scope,
        'scope' => $scope,
    ], $extra);

    if ($scope === 'company' && !empty($companyId)) {
        $params['company_id'] = (int)$companyId;
    }

    return http_build_query($params);
}

/*
|--------------------------------------------------------------------------
| Ownership logic by workspace
|--------------------------------------------------------------------------
*/
if ($is_all_workspace) {
    if (!empty($all_workspace_company_id)) {
        $ownershipSql = "d.company_id = :all_company_id";
    } else {
        $ownershipSql = "(d.user_id = :user_id OR d.company_id IN (
            SELECT company_id FROM company_users WHERE user_id = :user_id
        ))";
    }
} elseif ($is_company_workspace) {
    $ownershipSql = "d.company_id = :company_id";
} else {
    $ownershipSql = "d.user_id = :user_id AND d.company_id IS NULL";
}

/*
|--------------------------------------------------------------------------
| Query builder
|--------------------------------------------------------------------------
*/
$sql = "
    SELECT d.*, c.car_name, c.plate_number
    FROM documents d
    LEFT JOIN cars c ON d.car_id = c.id
    WHERE {$ownershipSql}
      AND d.is_deleted = 0
";

$params = [];

if ($is_all_workspace) {
    if (!empty($all_workspace_company_id)) {
        $params[':all_company_id'] = [$all_workspace_company_id, PDO::PARAM_INT];
    } else {
        $params[':user_id'] = [$user_id, PDO::PARAM_INT];
    }
} elseif ($is_company_workspace) {
    $params[':company_id'] = [$active_company_id, PDO::PARAM_INT];
} else {
    $params[':user_id'] = [$user_id, PDO::PARAM_INT];
}

if ($search !== '') {
    $sql .= "
      AND (
            d.category LIKE :search
            OR d.custom_name LIKE :search
            OR d.document_number LIKE :search
            OR d.issuer LIKE :search
            OR d.status LIKE :search
            OR d.entity_type LIKE :search
            OR d.original_file_name LIKE :search
            OR d.note LIKE :search
            OR c.car_name LIKE :search
            OR c.plate_number LIKE :search
      )
    ";

    $params[':search'] = ['%' . $search . '%', PDO::PARAM_STR];
}

$sql .= " ORDER BY d.id DESC ";

$stmt = $db->prepare($sql);

foreach ($params as $key => [$value, $type]) {
    $stmt->bindValue($key, $value, $type);
}

$stmt->execute();
$documents = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($reminder === 'now') {
    $documents = array_filter($documents, function ($doc) {
        return getReminderStatus($doc['expiry_date'] ?? '', $doc['category'] ?? '') === 'Remind now';
    });

    $documents = array_values($documents);
}

/*
|--------------------------------------------------------------------------
| Sort: Remind now first
|--------------------------------------------------------------------------
*/
usort($documents, function ($a, $b) {
    $statusA = getReminderStatus($a['expiry_date'] ?? '', $a['category'] ?? '');
    $statusB = getReminderStatus($b['expiry_date'] ?? '', $b['category'] ?? '');

    $priority = [
        'Remind now' => 0,
        'Waiting' => 1,
        '-' => 2
    ];

    $rankA = $priority[$statusA] ?? 99;
    $rankB = $priority[$statusB] ?? 99;

    if ($rankA !== $rankB) {
        return $rankA <=> $rankB;
    }

    return strcmp($a['expiry_date'] ?? '', $b['expiry_date'] ?? '');
});

$remindNowCount = 0;
foreach ($documents as $doc) {
    if (getReminderStatus($doc['expiry_date'] ?? '', $doc['category'] ?? '') === 'Remind now') {
        $remindNowCount++;
    }
}

function getCategoryTitle(string $category): string
{
    $category = trim($category);

    if ($category === '') {
        return 'All Documents';
    }

    return ucwords(str_replace(['_', '-'], ' ', $category));
}
?>
<!DOCTYPE html>
<html lang="en">
    
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Documents</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <style>



html, body {
    height: auto;
    overflow-y: auto;
}

.hero,
.card {
    width: 100%;
}

.table-wrap {
    min-width: 0;
}
.table-wrap {
    width: 100%;
    overflow-x: auto;
}

.admin-table {
    width: 100%;
    min-width: 1300px;
}

.admin-table th,
.admin-table td {
    white-space: nowrap;
    font-size: 13px;
    padding: 8px 10px;
}

.admin-table td.note-col {
    max-width: 220px;
    overflow: hidden;
    text-overflow: ellipsis;
}

.action-group {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}

.hero-header-mobile {
    min-width: 0;
}

.title-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}

.title-row h1 {
    margin: 0;
}

.workspace-badge {
    display: inline-flex;
    align-items: center;
    padding: 8px 12px;
    border-radius: 999px;
    font-size: 13px;
    font-weight: 700;
    background: #eff8ff;
    color: #175cd3;
    border: 1px solid #b2ddff;
    margin-top: 12px;
}

.mobile-menu-toggle {
    display: none;
    position: relative;
    width: 40px;
    height: 40px;
    flex: 0 0 40px;
    border: 1px solid #d0d5dd;
    border-radius: 10px;
    background: #fff;
    cursor: pointer;
    padding: 0;
}

.mobile-menu-toggle span {
    position: absolute;
    left: 10px;
    width: 18px;
    height: 2px;
    background: #2563eb;
    border-radius: 999px;
    transition: all 0.22s ease;
}

.mobile-menu-toggle span:nth-child(1) { top: 12px; }
.mobile-menu-toggle span:nth-child(2) { top: 18px; }
.mobile-menu-toggle span:nth-child(3) { top: 24px; }

.mobile-overlay {
    display: none;
}

.filter-bar {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: nowrap;
    width: 100%;
    padding: 14px;
    border: 1px solid #e4e7ec;
    border-radius: 16px;
    background: #f8fafc;
    box-shadow: 0 1px 2px rgba(16, 24, 40, 0.04);
}

.filter-field {
    flex: 0 0 auto;
    min-width: 0;
}

.filter-search-wrap {
    flex: 1 1 auto;
    min-width: 0;
}

.filter-input,
.filter-select {
    width: 100%;
    height: 46px;
    padding: 0 14px;
    border: 1px solid #d0d5dd;
    border-radius: 12px;
    background: #fff;
    font-size: 14px;
    color: #101828;
    outline: none;
    box-sizing: border-box;
}

.filter-select {
    min-width: 190px;
}

.filter-btn {
    height: 46px;
    padding: 0 18px;
    border-radius: 12px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    white-space: nowrap;
    font-weight: 600;
    box-sizing: border-box;
}
.row-remind {
    background: #fff1f1;
}

.row-remind:hover {
    background: #ffe4e4;
}

.topbar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 64px;
    background: #081225;
    border-bottom: 1px solid rgba(255,255,255,0.08);
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20px;
    z-index: 1000;
}



@media (max-width: 768px) {
    .layout {
        display: block;
    }

  

    .sidebar.open {
        transform: translateX(0);
    }

    .mobile-overlay.show {
        display: block;
        position: fixed;
        inset: 0;
        background: rgba(15, 23, 42, 0.45);
        z-index: 999;
    }

    .main {
        width: 100%;
        margin-left: 0 !important;
        padding-left: 0 !important;
    }

    .mobile-menu-toggle {
        display: inline-block;
    }

    .hero,
    .card {
        margin-left: 0 !important;
        width: 100%;
        box-sizing: border-box;
    }

    .hero-top {
        display: block;
    }

    .welcome-badge {
        margin-top: 10px;
    }

    .title-row h1 {
        font-size: 30px;
        line-height: 1.15;
    }

    .workspace-badge {
        margin-top: 8px;
        font-size: 12px;
        padding: 6px 10px;
    }

    .filter-bar {
        flex-wrap: wrap;
    }

    .filter-search-wrap {
        flex: 1 1 100%;
        width: 100%;
    }

    .filter-field {
        flex: 1 1 220px;
    }
}

@media (max-width: 640px) {
    .filter-bar {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
        padding: 10px;
        border-radius: 14px;
    }

    .filter-search-wrap,
    .filter-field {
        grid-column: 1 / -1;
        width: 100%;
    }

    .filter-input,
    .filter-select,
    .filter-btn {
        width: 100%;
        min-width: 0;
        height: 44px;
        font-size: 16px;
    }

    .filter-btn {
        padding: 0 12px;
    }
}
    </style>
</head>
<body>



<div class="layout">
    <?php include 'nav.php'; ?>

    <main class="main">
       
        <div class="mobile-overlay" id="mobileOverlay" onclick="closeSidebar()"></div>
       
        <div class="hero">
            <div class="hero-top">
              <div class="hero-header-mobile">
                    <div class="title-row">
                        <h1><?php echo htmlspecialchars(getCategoryTitle($category)); ?></h1>

                        <button class="mobile-menu-toggle" onclick="toggleSidebar()">
                            <span></span>
                            <span></span>
                            <span></span>
                        </button>
                    </div>

                    <div class="workspace-badge">
                        Viewing: <?php echo htmlspecialchars($workspace_label); ?>
                    </div>

                    <p>Manage your uploaded files and track issue dates, expiry dates, and reminders.</p>
                </div>
                <div class="welcome-badge">
                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?>
                </div>
            </div>
        </div>

        <div class="card">
            <form method="GET" class="filter-bar">
    <input type="hidden" name="workspace" value="<?php echo htmlspecialchars($scope); ?>">
    <input type="hidden" name="scope" value="<?php echo htmlspecialchars($scope); ?>">
        <?php if ($is_company_workspace && !empty($active_company_id)): ?>
            <input type="hidden" name="company_id" value="<?php echo (int)$active_company_id; ?>">
        <?php endif; ?>

    <div class="filter-field filter-search-wrap">
        <input
            type="text"
            name="search"
            placeholder="Search documents..."
            value="<?php echo htmlspecialchars($search); ?>"
            class="filter-input"
        >
    </div>

    <div class="filter-field">
        <select name="category" class="filter-select">
            <option value="">All Categories</option>
            <option value="contract" <?php echo $category === 'contract' ? 'selected' : ''; ?>>Contract</option>
            <option value="insurance" <?php echo $category === 'insurance' ? 'selected' : ''; ?>>Insurance</option>
            <option value="passport" <?php echo $category === 'passport' ? 'selected' : ''; ?>>Passport</option>
            <option value="license" <?php echo $category === 'license' ? 'selected' : ''; ?>>License</option>
            <option value="loan" <?php echo $category === 'loan' ? 'selected' : ''; ?>>Loan</option>
            <option value="personal_id" <?php echo $category === 'personal_id' ? 'selected' : ''; ?>>Personal ID</option>
            <option value="car_registration" <?php echo $category === 'car_registration' ? 'selected' : ''; ?>>Car Registration</option>
        </select>
    </div>

    <button class="btn btn-primary filter-btn" type="submit">Search</button>

    <a
        href="my_documents.php?<?php echo htmlspecialchars(workspaceQueryString($scope, $active_company_id)); ?>"
        class="btn btn-secondary filter-btn"
    >
        Clear
    </a>
</form>
        </div>

        <?php if ($remindNowCount > 0): ?>
            <a
                href="my_documents.php?<?php echo htmlspecialchars(workspaceQueryString($scope, $active_company_id, ['reminder' => 'now'])); ?>"
                class="card"
                style="display:block; background:#fff1f1; color:#b42318; text-decoration:none;"
            >
                ⚠️ <strong><?php echo $remindNowCount; ?></strong>
                document(s) need renewal now. Click to view.
            </a>
        <?php endif; ?>

        <div class="card">
            <div style="display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap; margin-bottom:8px;">
                <div>
                    <div class="section-title"><?php echo htmlspecialchars(getCategoryTitle($category)); ?></div>
                    <div class="section-subtext">
                        Total: <strong><?php echo count($documents); ?></strong> document(s)
                        <?php if ($is_all_workspace): ?>
                            across all workspaces
                        <?php elseif ($is_company_workspace): ?>
                            in <?php echo htmlspecialchars($company_name !== '' ? $company_name : 'company'); ?> workspace
                        <?php else: ?>
                            in personal workspace
                        <?php endif; ?>
                    </div>
                </div>

                <a href="upload_document.php?<?php echo htmlspecialchars(workspaceQueryString($scope, $active_company_id)); ?>" class="btn btn-primary">
                    + Upload New Document
                </a>
            </div>

            <div class="table-wrap">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Category</th>
                            
                            
                            <th>Name</th>
                            <th>Number</th>
                            <th>Issuer</th>
                            <th>Issue Date</th>
                            <th>Expiry Date</th>
                            <th>Days</th>
                            <th>Status</th>
                            <th>Reminder</th>
                            <th>File</th>
                            <th>Note</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($documents)): ?>

                            <?php $docNumber = 1; ?>
                            <?php foreach ($documents as $doc): ?>
                                <?php $reminderStatus = getReminderStatus($doc['expiry_date'] ?? '', $doc['category'] ?? ''); ?>
                                <tr class="<?php echo $reminderStatus === 'Remind now' ? 'row-remind' : ''; ?>">
                                    <td><span class="chip"><?php echo $docNumber; ?></span></td>
                                    <td><?php echo htmlspecialchars($doc['category'] ?? '-'); ?></td>
                               

                                    <td><?php echo htmlspecialchars($doc['custom_name'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars($doc['document_number'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars($doc['issuer'] ?? '-'); ?></td>
                                    <td><?php echo htmlspecialchars(formatDateForDisplay($doc['issue_date'] ?? '')); ?></td>
                                    <td><?php echo htmlspecialchars(formatDateForDisplay($doc['expiry_date'] ?? '')); ?></td>

                                    <td>
                                        <span class="days-badge <?php echo htmlspecialchars(getDaysLeftClass($doc['expiry_date'] ?? '')); ?>">
                                            <?php echo htmlspecialchars(formatDaysLeft($doc['expiry_date'] ?? '')); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <span class="badge info">
                                            <?php echo htmlspecialchars($doc['status'] ?? 'active'); ?>
                                        </span>
                                    </td>

                                    <td>
                                        <?php if ($reminderStatus === 'Remind now'): ?>
                                            <span class="badge danger">Remind now</span>
                                        <?php elseif ($reminderStatus === 'Waiting'): ?>
                                            <span class="badge info">Waiting</span>
                                        <?php else: ?>
                                            <span class="muted">-</span>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <?php if (!empty($doc['file_path'])): ?>
                                            <a class="link-btn" href="<?php echo htmlspecialchars($doc['file_path']); ?>" target="_blank">View</a>
                                        <?php else: ?>
                                            <span class="muted">No file</span>
                                        <?php endif; ?>
                                    </td>

                                    <td class="note-col"><?php echo htmlspecialchars($doc['note'] ?? '-'); ?></td>

                                    <td>
                                        <div class="action-group">
                                            <a class="btn btn-secondary btn-sm" href="edit_document.php?<?php echo htmlspecialchars(workspaceQueryString($scope, $active_company_id, ['id' => (int)$doc['id']])); ?>">
                                                Edit
                                            </a>

                                            <?php if (!empty($doc['file_path'])): ?>
                                                <a class="btn btn-success btn-sm" href="<?php echo htmlspecialchars($doc['file_path']); ?>" target="_blank">
                                                    Open
                                                </a>
                                            <?php endif; ?>

                                            <a class="btn btn-danger btn-sm"
   href="delete_document.php?<?php echo htmlspecialchars(workspaceQueryString($scope, $active_company_id, ['id' => (int)$doc['id']])); ?>"
                                               onclick="return confirm('Are you sure you want to delete this document?');">
                                               Delete
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php $docNumber++; ?>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="15">
                                    <div class="empty-state">No documents found.</div>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
</div>

<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('mobileOverlay');

    sidebar.classList.toggle('open');
    overlay.classList.toggle('show');
}

function closeSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('mobileOverlay');

    sidebar.classList.remove('open');
    overlay.classList.remove('show');
}
</script>
</body>
</html> 