<?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'];

$employees = reimbursement_load_employees($conn);
$employeeOptions = [];
foreach ($employees as $employee) {
    $id = (int) ($employee['id'] ?? 0);
    $code = trim((string) ($employee['employee_code'] ?? $employee['employee_id'] ?? $id));
    $employeeOptions[$id] = reimbursement_employee_name($employee) . ' (' . $code . ')';
}

$reimbursementTypes = [
    'Travel',
    'Food',
    'Fuel',
    'Internet',
    'Medical',
    'Office Supplies',
    'Phone',
    'Stay',
];

$errors = [];
$success = '';
$formData = [
    'employee_id' => '',
    'claim_month' => date('Y-m'),
    'notes' => '',
];
$itemRows = [[
    'reimbursement_type' => '',
    'bill_date' => '',
    'bill_number' => '',
    'claim_amount' => '',
    'approved_amount' => '',
]];

if (count($employeeOptions) === 1) {
    $formData['employee_id'] = (string) array_key_first($employeeOptions);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData['employee_id'] = (string) ($_POST['employee_id'] ?? '');
    $formData['claim_month'] = trim((string) ($_POST['claim_month'] ?? ''));
    $formData['notes'] = trim((string) ($_POST['notes'] ?? ''));

    $types = $_POST['reimbursement_type'] ?? [];
    $billDates = $_POST['bill_date'] ?? [];
    $billNumbers = $_POST['bill_number'] ?? [];
    $claimAmounts = $_POST['claim_amount'] ?? [];
    $approvedAmounts = $_POST['approved_amount'] ?? [];

    $employeeId = (int) $formData['employee_id'];
    if ($employeeId <= 0) {
        $errors[] = 'Select an employee.';
    }
    if ($formData['claim_month'] === '') {
        $errors[] = 'Select a claim month.';
    }

    $itemRows = [];
    foreach ($types as $index => $typeValue) {
        $row = [
            'reimbursement_type' => trim((string) $typeValue),
            'bill_date' => trim((string) ($billDates[$index] ?? '')),
            'bill_number' => trim((string) ($billNumbers[$index] ?? '')),
            'claim_amount' => trim((string) ($claimAmounts[$index] ?? '')),
            'approved_amount' => trim((string) ($approvedAmounts[$index] ?? '')),
        ];
        $itemRows[] = $row;
    }

    $items = [];
    foreach ($itemRows as $index => $row) {
        $claimAmount = (float) ($row['claim_amount'] !== '' ? $row['claim_amount'] : 0);
        $approvedAmount = (float) ($row['approved_amount'] !== '' ? $row['approved_amount'] : 0);
        if ($row['reimbursement_type'] === '' && $claimAmount <= 0 && $approvedAmount <= 0) {
            continue;
        }

        if ($row['reimbursement_type'] === '') {
            $errors[] = 'Choose a reimbursement type for each bill row.';
            continue;
        }
        if ($claimAmount <= 0) {
            $errors[] = 'Enter a valid claim amount for each reimbursement row.';
            continue;
        }

        $items[] = [
            'type' => $row['reimbursement_type'],
            'bill_date' => $row['bill_date'] !== '' ? $row['bill_date'] : null,
            'bill_number' => $row['bill_number'] !== '' ? $row['bill_number'] : null,
            'claim_amount' => $claimAmount,
            'approved_amount' => $approvedAmount > 0 ? $approvedAmount : $claimAmount,
        ];
    }

    if (!$items) {
        $errors[] = 'Add at least one reimbursement bill.';
    }

    if (empty($errors)) {
        $claimMonthDate = $formData['claim_month'] . '-01';
        $totalClaim = array_sum(array_column($items, 'claim_amount'));
        $totalApproved = array_sum(array_column($items, 'approved_amount'));

        $claimStmt = $conn->prepare("INSERT INTO reimbursement_claims (org_id, employee_id, claim_month, status, total_claim_amount, total_approved_amount, notes)
                                     VALUES (?, ?, ?, 'pending', ?, ?, ?)");
        if ($claimStmt) {
            $claimStmt->bind_param('sisdds', $orgId, $employeeId, $claimMonthDate, $totalClaim, $totalApproved, $formData['notes']);
            if ($claimStmt->execute()) {
                $claimId = (int) $claimStmt->insert_id;
                $claimStmt->close();

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

                $itemStmt = $conn->prepare("INSERT INTO reimbursement_items
                    (claim_id, reimbursement_type, bill_date, bill_number, attachment_path, claim_amount, approved_amount)
                    VALUES (?, ?, ?, ?, ?, ?, ?)");

                if ($itemStmt) {
                    foreach ($items as $index => $item) {
                        $attachmentPath = null;
                        if (!empty($_FILES['attachment']['tmp_name'][$index])) {
                            $tmp = $_FILES['attachment']['tmp_name'][$index];
                            $safeName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', basename($_FILES['attachment']['name'][$index]));
                            $destination = $uploadDir . '/' . $safeName;
                            if (move_uploaded_file($tmp, $destination)) {
                                $attachmentPath = 'uploads/reimbursements/' . $safeName;
                            }
                        }

                        $itemStmt->bind_param(
                            'issssdd',
                            $claimId,
                            $item['type'],
                            $item['bill_date'],
                            $item['bill_number'],
                            $attachmentPath,
                            $item['claim_amount'],
                            $item['approved_amount']
                        );
                        $itemStmt->execute();
                    }
                    $itemStmt->close();
                }

                header('Location: reimbursements.php?status=pending');
                exit();
            }
            $claimStmt->close();
        }

        $errors[] = 'Unable to save the claim right now.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Claim | 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-create-page">
<div class="dash-layout">
    <aside class="dash-sidebar reimburse-sidebar compact">
        <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 compact-start">
                    <div class="gs-top"><i class="fa-solid fa-sparkles"></i><span>Getting Started</span></div>
                </div>
            </div>
            <nav class="sidebar-nav compact-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>
                <a class="nav-item" href="form16.php"><i class="fa-regular fa-file-lines"></i><span>Form 16</span></a>
                <a class="nav-item" href="loans.php"><i class="fa-solid fa-indian-rupee-sign"></i><span>Loans</span></a>
                <a class="nav-item" href="giving.php"><i class="fa-regular fa-heart"></i><span>Giving</span></a>
                <a class="nav-item" href="documents.php"><i class="fa-regular fa-folder-open"></i><span>Documents</span></a>
                <a class="nav-item" href="reports.php"><i class="fa-regular fa-chart-bar"></i><span>Reports</span></a>
            </nav>
        </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-form-page">
            <div class="form-head">
                <h1>New Claim</h1>
                <a class="close-circle" href="reimbursements.php"><i class="fa-solid fa-xmark"></i></a>
            </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 method="POST" enctype="multipart/form-data" class="claim-form modern-form">
                <input type="hidden" name="claim_month" value="<?php echo htmlspecialchars($formData['claim_month']); ?>">
                <input type="hidden" name="notes" value="<?php echo htmlspecialchars($formData['notes']); ?>">

                <div class="hero-select">
                    <div class="field employee-field">
                        <label for="employee_id">Employee Name</label>
                        <select id="employee_id" name="employee_id" required>
                            <option value="">Select an Employee</option>
                            <?php foreach ($employeeOptions as $id => $label): ?>
                                <option value="<?php echo $id; ?>" <?php echo (string) $id === $formData['employee_id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (empty($employeeOptions)): ?>
                            <p class="employee-empty-note">No employees found. <a href="employees.php">Add employee</a> first.</p>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="items-head">
                    <div>Reimbursement Type <span>*</span></div>
                    <div>Bill Date</div>
                    <div>Bill Number</div>
                    <div>Attachments</div>
                    <div>Claim Amount <span>*</span></div>
                    <div>Approved Amount <span>*</span></div>
                </div>

                <div class="items-body" id="itemsBody">
                    <?php foreach ($itemRows as $rowIndex => $row): ?>
                        <div class="item-row">
                            <select name="reimbursement_type[]">
                                <option value="">Select Type</option>
                                <?php foreach ($reimbursementTypes as $type): ?>
                                    <option value="<?php echo htmlspecialchars($type); ?>" <?php echo $row['reimbursement_type'] === $type ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($type); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input type="date" name="bill_date[]" value="<?php echo htmlspecialchars($row['bill_date']); ?>">
                            <input type="text" name="bill_number[]" value="<?php echo htmlspecialchars($row['bill_number']); ?>" placeholder="Bill Number">
                            <input type="file" name="attachment[]">
                            <input type="number" step="0.01" min="0" name="claim_amount[]" value="<?php echo htmlspecialchars($row['claim_amount']); ?>" placeholder="0.00">
                            <input type="number" step="0.01" min="0" name="approved_amount[]" value="<?php echo htmlspecialchars($row['approved_amount']); ?>" placeholder="0.00">
                        </div>
                    <?php endforeach; ?>
                </div>

                <button class="link-btn" type="button" id="addRow"><i class="fa-solid fa-plus"></i> Add another bill</button>

                <div class="form-actions sticky-actions">
                    <button class="btn-primary" type="submit">Save & Approve</button>
                    <a class="btn-outline" href="reimbursements.php">Cancel</a>
                </div>
            </form>

            <div class="req-note">* indicates mandatory fields</div>
        </section>
    </main>
</div>

<template id="itemRowTemplate">
    <div class="item-row">
        <select name="reimbursement_type[]">
            <option value="">Select Type</option>
            <?php foreach ($reimbursementTypes as $type): ?>
                <option value="<?php echo htmlspecialchars($type); ?>"><?php echo htmlspecialchars($type); ?></option>
            <?php endforeach; ?>
        </select>
        <input type="date" name="bill_date[]">
        <input type="text" name="bill_number[]" placeholder="Bill Number">
        <input type="file" name="attachment[]">
        <input type="number" step="0.01" min="0" name="claim_amount[]" placeholder="0.00">
        <input type="number" step="0.01" min="0" name="approved_amount[]" placeholder="0.00">
    </div>
</template>

<script>
  (function(){
    const addRowButton = document.getElementById('addRow');
    const itemsBody = document.getElementById('itemsBody');
    const rowTemplate = document.getElementById('itemRowTemplate');
    if (!addRowButton || !itemsBody || !rowTemplate) return;

    addRowButton.addEventListener('click', function(){
      const fragment = rowTemplate.content.cloneNode(true);
      itemsBody.appendChild(fragment);
    });
  })();
</script>
</body>
</html>
