<?php
/**
 * Import employee transfers from CSV (same format as backup)
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

$pageTitle = 'Import Manpower Transfers';
$currentModule = 'transfer';

$errors = [];
$successMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        $errors[] = 'Please select a valid CSV file.';
    } else {
        $fileTmp = $_FILES['csv_file']['tmp_name'];

        if (!is_uploaded_file($fileTmp)) {
            $errors[] = 'File upload error.';
        } else {
            try {
                $db = getDB();
                $db->beginTransaction();

                $handle = fopen($fileTmp, 'r');
                if ($handle === false) {
                    throw new Exception('Unable to open uploaded file.');
                }

                // Read header
                $header = fgetcsv($handle);
                if ($header === false) {
                    throw new Exception('CSV file is empty.');
                }

                // Expected columns (same order as backup)
                $expected = [
                    'transfer_id',
                    'employee_id',
                    'employee_category',
                    'from_site_id',
                    'from_location',
                    'to_site_id',
                    'to_location',
                    'transfer_date',
                    'effective_branch',
                    'effective_attendance',
                    'esi_applicability',
                    'transfer_form_filled',
                    'approved_by_district_head',
                    'transfer_reason',
                    'transfer_status',
                    'created_at',
                    'approved_at',
                ];

                // Simple header validation (optional)
                if (count($header) < count($expected)) {
                    throw new Exception('CSV format does not match expected backup format.');
                }

                $insertSql = "
                    INSERT INTO employee_transfers (
                        employee_id,
                        employee_category,
                        from_site_id,
                        from_location,
                        to_site_id,
                        to_location,
                        transfer_date,
                        effective_branch,
                        effective_attendance,
                        esi_applicability,
                        transfer_form_filled,
                        approved_by_district_head,
                        transfer_reason,
                        transfer_status,
                        created_at,
                        approved_at
                    ) VALUES (
                        :employee_id,
                        :employee_category,
                        :from_site_id,
                        :from_location,
                        :to_site_id,
                        :to_location,
                        :transfer_date,
                        :effective_branch,
                        :effective_attendance,
                        :esi_applicability,
                        :transfer_form_filled,
                        :approved_by_district_head,
                        :transfer_reason,
                        :transfer_status,
                        :created_at,
                        :approved_at
                    )
                ";

                $stmt = $db->prepare($insertSql);
                $imported = 0;

                while (($row = fgetcsv($handle)) !== false) {
                    // Skip empty lines
                    if (count($row) === 0 || (count($row) === 1 && trim($row[0]) === '')) {
                        continue;
                    }

                    $data = array_combine($expected, array_slice($row, 0, count($expected)));

                    $employeeId = (int)($data['employee_id'] ?? 0);
                    $toSiteId = (int)($data['to_site_id'] ?? 0);
                    if ($employeeId <= 0 || $toSiteId <= 0) {
                        continue;
                    }

                    $stmt->execute([
                        ':employee_id' => $employeeId,
                        ':employee_category' => $data['employee_category'] ?? null,
                        ':from_site_id' => (int)($data['from_site_id'] ?? 0),
                        ':from_location' => $data['from_location'] ?? null,
                        ':to_site_id' => $toSiteId,
                        ':to_location' => $data['to_location'] ?? null,
                        ':transfer_date' => $data['transfer_date'] ?: date('Y-m-d'),
                        ':effective_branch' => $data['effective_branch'] ?: null,
                        ':effective_attendance' => $data['effective_attendance'] ?: null,
                        ':esi_applicability' => $data['esi_applicability'] ?: null,
                        ':transfer_form_filled' => ($data['transfer_form_filled'] ?? 'No') === 'Yes' ? 'Yes' : 'No',
                        ':approved_by_district_head' => $data['approved_by_district_head'] ?: null,
                        ':transfer_reason' => $data['transfer_reason'] ?? null,
                        ':transfer_status' => $data['transfer_status'] ?: 'pending',
                        ':created_at' => $data['created_at'] ?: date('Y-m-d H:i:s'),
                        ':approved_at' => $data['approved_at'] ?: null,
                    ]);

                    $imported++;
                }

                fclose($handle);
                $db->commit();

                $successMessage = "Successfully imported {$imported} transfer(s).";

            } catch (Exception $e) {
                if (isset($db) && $db->inTransaction()) {
                    $db->rollBack();
                }
                $errors[] = 'Import error: ' . $e->getMessage();
            }
        }
    }
}

include __DIR__ . '/../../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Import Manpower Transfers (CSV)</h2>
        <a href="<?php echo BASE_URL; ?>/modules/transfer/report.php" class="btn btn-secondary btn-sm">Back to Report</a>
    </div>

    <?php if (!empty($successMessage)): ?>
        <div class="alert alert-success">
            <span class="alert-icon">✓</span>
            <span class="alert-message"><?php echo htmlspecialchars($successMessage); ?></span>
        </div>
    <?php endif; ?>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <ul style="margin: 0; padding-left: 18px;">
                <?php foreach ($errors as $e): ?>
                    <li><?php echo htmlspecialchars($e); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <div style="margin-top: 10px;">
        <p style="color: var(--text-secondary); font-size: 13px; margin-bottom: 10px;">
            Use the <strong>Backup (CSV)</strong> button in the report to download a template. 
            You can modify that file and upload it here to re-import transfers.
        </p>

        <form method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <label class="form-label" for="csv_file">CSV File</label>
                <input type="file" id="csv_file" name="csv_file" class="form-control" accept=".csv" required>
            </div>

            <div style="margin-top: 20px; text-align: right;">
                <button type="submit" class="btn btn-primary">Import Transfers</button>
            </div>
        </form>
    </div>
</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>


