<?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/reimbursements_module.php';

ensure_reimbursements_schema($conn);
$orgContext = reimbursement_org_context($conn);
$orgName = $orgContext['org_name'];
$orgId = (string) $orgContext['org_id'];

$errors = [];
$success = '';
$selectedEncoding = 'UTF-8 (Unicode)';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $selectedEncoding = trim((string) ($_POST['encoding_name'] ?? 'UTF-8 (Unicode)'));

    if (empty($_FILES['import_file']['tmp_name'])) {
        $errors[] = 'Choose a file to import.';
    } else {
        $fileName = basename((string) $_FILES['import_file']['name']);
        $fileSize = (int) ($_FILES['import_file']['size'] ?? 0);
        $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        if (!in_array($extension, ['csv', 'tsv', 'xls', 'xlsx'], true)) {
            $errors[] = 'Upload a CSV, TSV, XLS, or XLSX file.';
        }
        if ($fileSize > 5 * 1024 * 1024) {
            $errors[] = 'The selected file is larger than 5 MB.';
        }

        if (empty($errors)) {
            $uploadDir = __DIR__ . '/uploads/reimbursements/imports';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $safeName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $fileName);
            $destination = $uploadDir . '/' . $safeName;
            if (move_uploaded_file($_FILES['import_file']['tmp_name'], $destination)) {
                $relativePath = 'uploads/reimbursements/imports/' . $safeName;
                $insert = $conn->prepare("INSERT INTO reimbursement_imports (org_id, file_name, file_path, file_format, encoding_name, imported_rows)
                                          VALUES (?, ?, ?, ?, ?, 0)");
                if ($insert) {
                    $insert->bind_param('sssss', $orgId, $fileName, $relativePath, $extension, $selectedEncoding);
                    $insert->execute();
                    $insert->close();
                }
                $success = 'File uploaded. Import review can be added next.';
            } else {
                $errors[] = 'Unable to save the uploaded file.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Import Reimbursements</title>
    <link rel="stylesheet" href="dashboard.css">
    <link rel="stylesheet" href="reimbursements.css">
    <link rel="stylesheet" href="assets/font-inter.css">
    <link rel="stylesheet" href="assets/fontawesome/css/all.min.css">
</head>
<body class="dash-page reimburse-shell reimburse-import-screen">
<div class="dash-layout">
    <aside class="dash-sidebar reimburse-sidebar">
        <div class="sidebar-brand">
            <img src="images/b2l_mobitech_pvt_ltd_logo.jpg" class="logo" alt="B2L Mobitech Pvt Ltd">
        </div>
        <div class="sidebar-scroll">
            <div class="sidebar-section">
                <div class="getting-started">
                    <div class="gs-top">
                        <i class="fa-solid fa-sparkles"></i>
                        <span>Getting Started</span>
                    </div>
                    <div class="progress-bar"><div class="progress-fill reimburse-progress"></div></div>
                </div>
            </div>
            <nav class="sidebar-nav">
                <a class="nav-item" href="dashboard.php"><i class="fa-regular fa-circle-dot"></i><span>Dashboard</span></a>
                <a class="nav-item" href="employees.php"><i class="fa-regular fa-user"></i><span>Employees</span></a>
                <a class="nav-item" href="payruns.php"><i class="fa-regular fa-calendar-check"></i><span>Pay Runs</span></a>
                <div class="nav-group open">
                    <button class="nav-item btn active" type="button"><i class="fa-regular fa-square-check"></i><span>Approvals</span></button>
                    <div class="nav-sub">
                        <a class="nav-sub-item active" href="reimbursements.php">Reimbursements</a>
                        <a class="nav-sub-item" href="proof_of_investments.php">Proof Of Investments</a>
                        <a class="nav-sub-item" href="salary_revision.php">Salary Revision</a>
                    </div>
                </div>
            </nav>
        </div>
        <div class="sidebar-footer">
            <a class="support-link" href="#">Contact Support</a>
        </div>
    </aside>

    <main class="dash-main">
        <header class="dash-topbar">
            <div class="search-box">
                <i class="fa-solid fa-magnifying-glass search-icon"></i>
                <input type="text" placeholder="Search in Employee">
            </div>
            <div class="topbar-actions">
                <span class="trial">Your trial expires in 1 day(s). <a href="dashboard.php?modal=upgrade">Upgrade</a></span>
                <a class="pill ghost org-toggle" href="#"><span class="pill-label"><?php echo htmlspecialchars($orgName); ?></span><i class="fa-solid fa-angle-down"></i></a>
                <a class="top-icon icon-btn" href="#"><i class="fa-regular fa-user-group"></i></a>
                <a class="top-icon icon-btn" href="#"><i class="fa-regular fa-bell"></i></a>
                <a class="top-icon top-link" href="settings.php"><i class="fa-solid fa-gear"></i></a>
                <span class="avatar"><?php echo strtoupper(substr($orgName, 0, 1)); ?></span>
                <a class="top-icon icon-btn" href="#"><i class="fa-solid fa-table-cells-large"></i></a>
            </div>
        </header>

        <section class="dash-content reimburse-import-page">
            <div class="import-head">
                <h1>Import Reimbursements - Select File</h1>
            </div>

            <?php if ($success !== ''): ?>
                <div class="alert-ok"><?php echo htmlspecialchars($success); ?></div>
            <?php endif; ?>
            <?php if (!empty($errors)): ?>
                <div class="alert-err">
                    <div class="alert-err-title">Please fix the following:</div>
                    <ul>
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form class="import-card" method="POST" enctype="multipart/form-data">
                <p class="import-copy">
                    Download a sample <a href="database/reimbursements_sample.csv" download>.csv format</a> or
                    <a href="database/reimbursements_sample.xls">.xls format</a> file and compare it with your import file to
                    ensure that the file is ready to import.
                </p>

                <label class="upload-box upload-large">
                    <input type="file" name="import_file" hidden>
                    <span class="upload-icon"><i class="fa-solid fa-cloud-arrow-up"></i></span>
                    <span class="upload-title">Drop files here or click here to upload</span>
                    <span class="upload-copy">Maximum File Size: 5 MB | File Format: CSV or TSV or XLS</span>
                </label>

                <div class="panel-field import-field">
                    <label for="encoding_name">Character Encoding <span>*</span></label>
                    <select id="encoding_name" name="encoding_name">
                        <option <?php echo $selectedEncoding === 'UTF-8 (Unicode)' ? 'selected' : ''; ?>>UTF-8 (Unicode)</option>
                        <option <?php echo $selectedEncoding === 'UTF-16' ? 'selected' : ''; ?>>UTF-16</option>
                        <option <?php echo $selectedEncoding === 'ISO-8859-1' ? 'selected' : ''; ?>>ISO-8859-1</option>
                    </select>
                </div>

                <div class="modal-actions import-actions">
                    <button class="btn-primary" type="submit">Next</button>
                    <a class="btn-outline" href="reimbursements.php">Cancel</a>
                    <div class="req-note left-note">* indicates mandatory fields</div>
                </div>
            </form>
        </section>
    </main>
</div>
</body>
</html>
