<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';

session_start();
if (empty($_SESSION['authenticated'])) {
    header("Location: signin.php");
    exit();
}

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/module_helpers.php';

$context = payroll_org_context($conn);
$employees = payroll_load_employees($conn);
$employeeMap = [];
foreach ($employees as $employee) {
    $employeeMap[(int) $employee['id']] = payroll_employee_name($employee) . ' (' . payroll_employee_code($employee) . ')';
}

$flashMessage = $_SESSION['flash_ok'] ?? '';
$flashError = $_SESSION['flash_err'] ?? '';
unset($_SESSION['flash_ok'], $_SESSION['flash_err']);

$requiredTables = ['document_folders', 'document_files'];
$missingTables = payroll_missing_tables($conn, $requiredTables);
$schemaReady = empty($missingTables);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$schemaReady) {
    payroll_redirect_with_flash('documents.php', 'Import database/workhub_modules.sql in phpMyAdmin before using Documents.', true);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_folder'])) {
    $scope = trim((string) ($_POST['folder_scope'] ?? 'org'));
    $folderName = trim((string) ($_POST['folder_name'] ?? ''));
    $description = trim((string) ($_POST['description'] ?? ''));
    $employeeId = (int) ($_POST['employee_id'] ?? 0);
    $employeeStatus = trim((string) ($_POST['employee_status'] ?? 'active'));

    if ($folderName === '' || $description === '') {
        payroll_redirect_with_flash('documents.php?modal=' . ($scope === 'employee' ? 'employee' : 'org'), 'Folder name and description are required.', true);
    }
    if ($scope === 'employee' && $employeeId <= 0) {
        payroll_redirect_with_flash('documents.php?modal=employee', 'Select an employee for employee folders.', true);
    }

    $stmt = $conn->prepare("INSERT INTO document_folders (org_id, folder_scope, folder_name, description, employee_id, employee_status)
                            VALUES (?, ?, ?, ?, ?, ?)");
    if (!$stmt) {
        payroll_redirect_with_flash('documents.php', 'Unable to prepare folder save.', true);
    }

    $employeeIdSql = $scope === 'employee' ? $employeeId : null;
    $statusSql = $scope === 'employee' ? $employeeStatus : 'all';
    $stmt->bind_param('ssssis', $context['org_id'], $scope, $folderName, $description, $employeeIdSql, $statusSql);
    if (!$stmt->execute()) {
        $message = 'Unable to save folder. ' . $stmt->error;
        $stmt->close();
        payroll_redirect_with_flash('documents.php', $message, true);
    }
    $stmt->close();

    payroll_redirect_with_flash('documents.php', 'Folder created successfully.');
}

$filters = [
    'employee_status' => trim((string) ($_GET['employee_status'] ?? '')),
    'employee_id' => (int) ($_GET['employee_id'] ?? 0),
];

$openFilter = trim((string) ($_GET['filter'] ?? ''));
$openModal = trim((string) ($_GET['modal'] ?? ''));
$selectedFolder = trim((string) ($_GET['folder'] ?? 'all'));

$orgFolders = [];
$employeeFolders = [];
if ($schemaReady) {
    $orgStmt = $conn->prepare("SELECT * FROM document_folders WHERE org_id = ? AND folder_scope = 'org' ORDER BY id DESC");
    if ($orgStmt) {
        $orgStmt->bind_param('s', $context['org_id']);
        $orgStmt->execute();
        $orgResult = $orgStmt->get_result();
        while ($row = $orgResult->fetch_assoc()) {
            $orgFolders[] = $row;
        }
        $orgStmt->close();
    }

    $sql = "SELECT * FROM document_folders WHERE org_id = ? AND folder_scope = 'employee'";
    $types = 's';
    $params = [$context['org_id']];
    if ($filters['employee_status'] !== '') {
        $sql .= " AND employee_status = ?";
        $types .= 's';
        $params[] = $filters['employee_status'];
    }
    if ($filters['employee_id'] > 0) {
        $sql .= " AND employee_id = ?";
        $types .= 'i';
        $params[] = $filters['employee_id'];
    }
    $sql .= " ORDER BY id DESC";

    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $bind = [$types];
        foreach ($params as $index => $value) {
            $params[$index] = $value;
            $bind[] = &$params[$index];
        }
        call_user_func_array([$stmt, 'bind_param'], $bind);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $employeeFolders[] = $row;
        }
        $stmt->close();
    }
}

$allFolders = array_merge($orgFolders, $employeeFolders);
$showEmptyState = count($allFolders) === 0;
$selectedStatusLabel = $filters['employee_status'] !== '' ? [
    'active' => 'Active Employees',
    'exited' => 'Exited Employees',
    'all' => 'All Employees',
][$filters['employee_status']] ?? 'Select Employee Status' : 'Select Employee Status';
$selectedEmployeeLabel = $filters['employee_id'] > 0 && isset($employeeMap[$filters['employee_id']])
    ? $employeeMap[$filters['employee_id']]
    : 'Select an Employee';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="<?php echo billing_escape(billing_base_href()); ?>">
    <title>Documents | Payroll</title>
    <link rel="stylesheet" href="dashboard.css">
    <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
    <link rel="stylesheet" href="assets/font-inter.css">
    <link rel="stylesheet" href="modules.css">
</head>
<body class="module-page">
<div class="module-shell docs-shell">
    <aside class="docs-icon-rail">
        <div class="docs-rail-top">
            <div class="docs-rail-brand">
                <img src="images/zoho-payroll-logo.svg" alt="Payroll">
            </div>
            <a href="#" class="docs-rail-item active"><i class="fa-regular fa-folder-open"></i></a>
        </div>
        <nav class="docs-rail-nav">
            <a href="dashboard.php" class="docs-rail-link">
                <i class="fa-regular fa-circle-dot"></i>
                <span>Dashboard</span>
            </a>
            <a href="employees.php" class="docs-rail-link">
                <i class="fa-regular fa-user"></i>
                <span>Employees</span>
            </a>
            <a href="payruns.php" class="docs-rail-link">
                <i class="fa-regular fa-calendar-check"></i>
                <span>Pay Runs</span>
            </a>
            <a href="#" class="docs-rail-link">
                <i class="fa-regular fa-square-check"></i>
                <span>Approvals</span>
            </a>
            <a href="form16.php" class="docs-rail-link">
                <i class="fa-regular fa-file-lines"></i>
                <span>Form 16</span>
            </a>
            <a href="loans.php" class="docs-rail-link">
                <i class="fa-solid fa-indian-rupee-sign"></i>
                <span>Loans</span>
            </a>
            <a href="giving.php" class="docs-rail-link">
                <i class="fa-regular fa-heart"></i>
                <span>Giving</span>
            </a>
            <a href="documents.php" class="docs-rail-link active">
                <i class="fa-regular fa-folder-open"></i>
                <span>Documents</span>
            </a>
        </nav>
        <div class="docs-rail-bottom">
            <a href="reports.php" class="docs-rail-link">
                <i class="fa-regular fa-chart-bar"></i>
                <span>Reports</span>
            </a>
            <a href="settings.php" class="docs-rail-link">
                <i class="fa-solid fa-gear"></i>
                <span>Settings</span>
            </a>
            <a href="#" class="docs-rail-link">
                <i class="fa-solid fa-right-from-bracket"></i>
                <span>More</span>
            </a>
        </div>
    </aside>

    <aside class="docs-folder-panel">
        <div class="docs-folder-topbar">
            <div class="module-search docs-search">
                <i class="fa-solid fa-magnifying-glass"></i>
                <input type="text" placeholder="Search in Employee">
            </div>
        </div>

        <div class="docs-folder-content">
            <div class="docs-folder-header">
                <h1>Documents</h1>
            </div>

            <a class="docs-folder-all <?php echo $selectedFolder === 'all' ? 'active' : ''; ?>" href="documents.php">
                <i class="fa-regular fa-folder-open"></i>
                <span>All Documents</span>
            </a>

            <section class="docs-folder-group">
                <div class="docs-folder-group-head">
                    <span>ORG FOLDER</span>
                    <a href="documents.php?modal=org" class="docs-plus-btn" aria-label="New Org Folder"><i class="fa-solid fa-plus"></i></a>
                </div>
                <?php if (!$orgFolders): ?>
                    <div class="docs-folder-empty-box">
                        <div class="docs-folder-empty-icon"><i class="fa-solid fa-folder"></i></div>
                        <p>There are no folders.</p>
                        <a class="docs-light-btn" href="documents.php?modal=org">+New folder</a>
                    </div>
                <?php else: ?>
                    <div class="docs-folder-list">
                        <?php foreach ($orgFolders as $folder): ?>
                            <a class="docs-folder-link" href="documents.php?folder=org-<?php echo (int) $folder['id']; ?>">
                                <i class="fa-regular fa-folder"></i>
                                <span><?php echo htmlspecialchars((string) $folder['folder_name']); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>

            <section class="docs-folder-group">
                <div class="docs-folder-group-head">
                    <span>EMPLOYEE FOLDER</span>
                    <a href="documents.php?modal=employee" class="docs-plus-btn" aria-label="New Employee Folder"><i class="fa-solid fa-plus"></i></a>
                </div>
                <?php if (!$employeeFolders): ?>
                    <div class="docs-folder-empty-box">
                        <div class="docs-folder-empty-icon"><i class="fa-solid fa-folder"></i></div>
                        <p>There are no folders.</p>
                        <a class="docs-light-btn" href="documents.php?modal=employee">+New folder</a>
                    </div>
                <?php else: ?>
                    <div class="docs-folder-list">
                        <?php foreach ($employeeFolders as $folder): ?>
                            <a class="docs-folder-link" href="documents.php?folder=employee-<?php echo (int) $folder['id']; ?>">
                                <i class="fa-regular fa-folder"></i>
                                <span><?php echo htmlspecialchars((string) $folder['folder_name']); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>

            <div class="docs-storage-card">
                <div class="docs-storage-icon"><i class="fa-solid fa-box-archive"></i></div>
                <div>
                    <div class="docs-storage-title">Storage Limit</div>
                    <div class="docs-storage-copy">1GB / 100 employees</div>
                </div>
            </div>

            <a class="docs-trash-link" href="#">
                <i class="fa-regular fa-trash-can"></i>
                <span>Trash</span>
            </a>
        </div>
    </aside>

    <main class="docs-main">
        <div class="docs-main-topbar">
            <div class="docs-main-right">
                <span class="docs-user-name"><?php echo htmlspecialchars($context['display_name']); ?></span>
                <span class="module-avatar"><?php echo htmlspecialchars(strtoupper(substr($context['display_name'], 0, 1))); ?></span>
            </div>
        </div>

        <?php if ($flashMessage): ?>
            <div class="alert ok docs-alert"><?php echo htmlspecialchars($flashMessage); ?></div>
        <?php endif; ?>
        <?php if ($flashError): ?>
            <div class="alert err docs-alert"><?php echo htmlspecialchars($flashError); ?></div>
        <?php endif; ?>
        <?php if (!$schemaReady): ?>
            <div class="alert err docs-alert">Missing tables: <?php echo htmlspecialchars(implode(', ', $missingTables)); ?>. Import <strong>database/workhub_modules.sql</strong> in phpMyAdmin first.</div>
        <?php endif; ?>

        <section class="docs-board">
            <div class="docs-board-head">
                <h2>All Documents</h2>
                <a class="docs-filter-icon" href="documents.php?filter=menu" aria-label="Filter"><i class="fa-solid fa-filter"></i></a>
            </div>

            <div class="docs-filter-row">
                <span class="docs-filter-label">FILTER BY :</span>

                <div class="docs-filter-block">
                    <a class="docs-filter-trigger" href="documents.php?filter=status<?php echo $filters['employee_id'] > 0 ? '&employee_id=' . $filters['employee_id'] : ''; ?>">
                        <i class="fa-regular fa-id-badge"></i>
                        <span><?php echo htmlspecialchars($selectedStatusLabel); ?></span>
                        <i class="fa-solid fa-angle-down"></i>
                    </a>
                    <?php if ($openFilter === 'status'): ?>
                        <div class="docs-dropdown-menu">
                            <div class="docs-dropdown-search">
                                <i class="fa-solid fa-magnifying-glass"></i>
                                <input type="text" placeholder="">
                            </div>
                            <a class="docs-dropdown-item <?php echo $filters['employee_status'] === 'active' ? 'active' : ''; ?>" href="documents.php?employee_status=active<?php echo $filters['employee_id'] > 0 ? '&employee_id=' . $filters['employee_id'] : ''; ?>">Active Employees</a>
                            <a class="docs-dropdown-item <?php echo $filters['employee_status'] === 'exited' ? 'active' : ''; ?>" href="documents.php?employee_status=exited<?php echo $filters['employee_id'] > 0 ? '&employee_id=' . $filters['employee_id'] : ''; ?>">Exited Employees</a>
                            <a class="docs-dropdown-item <?php echo $filters['employee_status'] === 'all' ? 'active' : ''; ?>" href="documents.php?employee_status=all<?php echo $filters['employee_id'] > 0 ? '&employee_id=' . $filters['employee_id'] : ''; ?>">All Employees</a>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="docs-filter-block">
                    <a class="docs-filter-trigger" href="documents.php?filter=employee<?php echo $filters['employee_status'] !== '' ? '&employee_status=' . urlencode($filters['employee_status']) : ''; ?>">
                        <i class="fa-regular fa-user"></i>
                        <span><?php echo htmlspecialchars($selectedEmployeeLabel); ?></span>
                        <i class="fa-solid fa-angle-down"></i>
                    </a>
                    <?php if ($openFilter === 'employee'): ?>
                        <div class="docs-dropdown-menu docs-dropdown-menu-scroll">
                            <div class="docs-dropdown-search">
                                <i class="fa-solid fa-magnifying-glass"></i>
                                <input type="text" placeholder="">
                            </div>
                            <?php foreach ($employeeMap as $employeeId => $label): ?>
                                <a class="docs-dropdown-item <?php echo $filters['employee_id'] === $employeeId ? 'active' : ''; ?>" href="documents.php?employee_id=<?php echo $employeeId; ?><?php echo $filters['employee_status'] !== '' ? '&employee_status=' . urlencode($filters['employee_status']) : ''; ?>">
                                    <?php echo htmlspecialchars($label); ?>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <a class="docs-close-filter" href="documents.php" aria-label="Clear Filter"><i class="fa-solid fa-xmark"></i></a>
            </div>

            <div class="docs-board-body">
                <?php if ($showEmptyState): ?>
                    <div class="docs-empty-state">
                        <div class="docs-empty-figure">
                            <div class="docs-empty-shadow"></div>
                            <div class="docs-empty-card"></div>
                            <div class="docs-empty-box"></div>
                            <div class="docs-empty-person"></div>
                        </div>
                        <p>You have not created any folders yet to upload documents</p>
                    </div>
                <?php else: ?>
                    <div class="docs-table-wrap">
                        <table class="module-table">
                            <thead>
                            <tr>
                                <th>Folder</th>
                                <th>Scope</th>
                                <th>Employee</th>
                                <th>Status</th>
                                <th>Description</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($allFolders as $folder): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars((string) $folder['folder_name']); ?></td>
                                    <td><?php echo htmlspecialchars(ucfirst((string) $folder['folder_scope'])); ?></td>
                                    <td><?php echo !empty($folder['employee_id']) ? htmlspecialchars($employeeMap[(int) $folder['employee_id']] ?? '-') : '-'; ?></td>
                                    <td><?php echo htmlspecialchars(ucfirst((string) ($folder['employee_status'] ?? 'all'))); ?></td>
                                    <td><?php echo htmlspecialchars((string) $folder['description']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </section>
    </main>
</div>

<?php if ($openModal === 'org' || $openModal === 'employee'): ?>
    <div class="docs-modal-backdrop">
        <div class="docs-modal">
            <div class="docs-modal-head">
                <h3><?php echo $openModal === 'employee' ? 'New Employee Folder' : 'New Org Folder'; ?></h3>
                <a class="icon-btn ghost" href="documents.php" aria-label="Close"><i class="fa-solid fa-xmark"></i></a>
            </div>
            <form method="post" class="docs-modal-form">
                <input type="hidden" name="create_folder" value="1">
                <input type="hidden" name="folder_scope" value="<?php echo $openModal === 'employee' ? 'employee' : 'org'; ?>">

                <div class="field-group full">
                    <label for="folder_name_modal">Folder Name <span class="req">*</span></label>
                    <input id="folder_name_modal" type="text" name="folder_name" required>
                </div>

                <div class="field-group full">
                    <label for="folder_desc_modal">Description <span class="req">*</span></label>
                    <textarea id="folder_desc_modal" name="description" required></textarea>
                </div>

                <?php if ($openModal === 'employee'): ?>
                    <div class="field-group">
                        <label for="employee_id_modal">Employee <span class="req">*</span></label>
                        <select id="employee_id_modal" name="employee_id" required>
                            <option value="0">Select an Employee</option>
                            <?php foreach ($employeeMap as $employeeId => $label): ?>
                                <option value="<?php echo $employeeId; ?>"><?php echo htmlspecialchars($label); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="field-group">
                        <label for="employee_status_modal">Employee Status</label>
                        <select id="employee_status_modal" name="employee_status">
                            <option value="active">Active Employees</option>
                            <option value="exited">Exited Employees</option>
                            <option value="all">All Employees</option>
                        </select>
                    </div>
                <?php endif; ?>

                <div class="docs-modal-foot">
                    <button class="btn-primary" type="submit">Save</button>
                    <a class="btn-secondary" href="documents.php">Cancel</a>
                </div>
            </form>
        </div>
    </div>
<?php endif; ?>
</body>
</html>

