<?php
// superadmin/import-excel.php
session_start();
require_once '../includes/config.php';
require_once '../includes/sa_auth.php';
require_once '../includes/db.php';
requireSuperAdmin();

$id = intval($_GET['id'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['excel_file']['tmp_name'])) {
    header("Location: manage-invitees.php?id=$id"); exit;
}

// Requires PhpSpreadsheet via Composer: composer require phpoffice/phpspreadsheet
require_once dirname(__DIR__) . '/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

try {
    $pdo         = getDB();
    $spreadsheet = IOFactory::load($_FILES['excel_file']['tmp_name']);
    $sheet       = $spreadsheet->getActiveSheet();
    $added       = 0;

    foreach ($sheet->getRowIterator(2) as $row) {
        $cells = $row->getCellIterator();
        $cells->setIterateOnlyExistingCells(false);
        $data = [];
        foreach ($cells as $cell) {
            $data[] = trim((string)$cell->getValue());
            if (count($data) >= 2) break;
        }
        $token = $data[0] ?? '';
        $name  = $data[1] ?? '';
        if (!$token || !$name) continue;

        $stmt = $pdo->prepare("SELECT id FROM invitations WHERE project_id=? AND token=?");
        $stmt->execute([$id, $token]);
        $inv = $stmt->fetch();
        if (!$inv) {
            $pdo->prepare("INSERT INTO invitations (project_id,token) VALUES (?,?)")->execute([$id, $token]);
            $inv_id = $pdo->lastInsertId();
        } else {
            $inv_id = $inv['id'];
        }
        $pdo->prepare("INSERT INTO invitees (invitation_id,name) VALUES (?,?)")->execute([$inv_id, $name]);
        $added++;
    }
    $_SESSION['import_msg'] = "$added invitees imported successfully from Excel!";
} catch (Exception $e) {
    $_SESSION['import_err'] = "Import failed: " . $e->getMessage();
}

header("Location: manage-invitees.php?id=$id");
