<?php
/**
 * Bulk importers for the newer add-on modules:
 *   - staff_pay          → payroll_staff_pay        (Payroll)
 *   - student_health     → student_health           (Health Records)
 *   - student_leadership → student_leadership        (Leadership & Activities)
 *   - student_activities → student_activities        (Leadership & Activities)
 *   - biometric_enroll   → biometric_enrollments     (Biometric Attendance)
 *
 * These plug into migration/imports/csv_import.php: moduleDetectType() maps a
 * filename to one of the types above (checked BEFORE the legacy student/staff/…
 * detection so "student_health.csv" / "staff_salary.csv" route correctly), and
 * moduleImportDispatch() runs the matching importer inside the existing import
 * transaction. Tables self-heal via the module libs, so imports work even on a
 * install where the migrations have not been run yet.
 */

require_once __DIR__ . '/../../includes/payroll_lib.php';
require_once __DIR__ . '/../../includes/health_lib.php';
require_once __DIR__ . '/../../includes/student_activities_lib.php';
require_once __DIR__ . '/../../includes/biometric_lib.php';

if (!function_exists('moduleDetectType')) {

    /** Map an uploaded filename to a module import type, or null. */
    function moduleDetectType(string $name): ?string
    {
        $n = strtolower($name);
        if (strpos($n, 'health') !== false || strpos($n, 'medical') !== false)   return 'student_health';
        if (strpos($n, 'leadership') !== false || strpos($n, 'prefect') !== false) return 'student_leadership';
        if (strpos($n, 'activit') !== false)                                       return 'student_activities';
        if (strpos($n, 'salary') !== false || strpos($n, 'payroll') !== false)     return 'staff_pay';
        if (strpos($n, 'biometric') !== false || strpos($n, 'fingerprint') !== false) return 'biometric_enroll';
        return null;
    }

    /** Human labels for the module import templates. */
    function moduleImportTemplates(): array
    {
        return [
            'staff_pay' => [
                'file'    => 'staff_pay_template.csv',
                'label'   => 'Staff Salaries (Payroll)',
                'headers' => ['staff_id','basic_salary','transport_allowance','housing_allowance','other_allowance','other_deductions','tax_relief','ssnit_exempt'],
            ],
            'student_health' => [
                'file'    => 'student_health_template.csv',
                'label'   => 'Student Health Records',
                'headers' => ['student_id','blood_group','genotype','allergies','conditions','medications','emergency_name','emergency_phone','emergency_relation','insurance_no'],
            ],
            'student_leadership' => [
                'file'    => 'student_leadership_template.csv',
                'label'   => 'Student Leadership Roles',
                'headers' => ['student_id','role','academic_year','term','note'],
            ],
            'student_activities' => [
                'file'    => 'student_activities_template.csv',
                'label'   => 'Student Activities',
                'headers' => ['student_id','activity_name','activity_type','academic_year','position','achievement'],
            ],
            'biometric_enroll' => [
                'file'    => 'biometric_enroll_template.csv',
                'label'   => 'Biometric Enrolment (fingerprint mapping)',
                'headers' => ['person_type','person_code','device_user_id'],
            ],
        ];
    }

    /** Dispatch a module import; returns the number of rows imported. */
    function moduleImportDispatch(string $type, string $file, mysqli $conn): int
    {
        switch ($type) {
            case 'staff_pay':          return importStaffPay($file, $conn);
            case 'student_health':     return importStudentHealth($file, $conn);
            case 'student_leadership': return importStudentLeadership($file, $conn);
            case 'student_activities': return importStudentActivitiesCsv($file, $conn);
            case 'biometric_enroll':   return importBiometricEnroll($file, $conn);
            default:                   return 0;
        }
    }

    // ── helpers ────────────────────────────────────────────────────────────
    function mod_val($row, $key) { $v = $row[$key] ?? null; if ($v === null) return null; $t = trim((string) $v); return ($t === '' || strtoupper($t) === 'N/A' || $t === '-') ? null : $t; }
    function mod_num($row, $key) { return (float) (mod_val($row, $key) ?? 0); }

    function mod_resolve_student(mysqli $conn, ?string $code): ?array
    {
        if ($code === null || $code === '') return null;
        $stmt = $conn->prepare("SELECT id, CONCAT(first_name,' ',last_name) name FROM students WHERE student_id=? OR id=? LIMIT 1");
        $idNum = ctype_digit($code) ? (int) $code : 0;
        $stmt->bind_param('si', $code, $idNum);
        $stmt->execute(); $r = $stmt->get_result()->fetch_assoc(); $stmt->close();
        return $r ?: null;
    }
    function mod_resolve_staff(mysqli $conn, ?string $code): ?array
    {
        if ($code === null || $code === '') return null;
        $stmt = $conn->prepare("SELECT id, full_name name FROM staff WHERE staff_id=? OR full_name=? OR id=? LIMIT 1");
        $idNum = ctype_digit($code) ? (int) $code : 0;
        $stmt->bind_param('ssi', $code, $code, $idNum);
        $stmt->execute(); $r = $stmt->get_result()->fetch_assoc(); $stmt->close();
        return $r ?: null;
    }

    // ── importers ──────────────────────────────────────────────────────────
    function importStaffPay(string $file, mysqli $conn): int
    {
        payroll_ensure_tables($conn);
        $h = fopen($file, 'r'); if (!$h) return 0;
        $headers = fgetcsv($h); $count = 0;
        while (($row = fgetcsv($h)) !== false) {
            $r = array_combine($headers, $row);
            $staff = mod_resolve_staff($conn, mod_val($r, 'staff_id') ?? mod_val($r, 'staff_name'));
            if (!$staff) continue;
            $basic = mod_num($r, 'basic_salary'); $tr = mod_num($r, 'transport_allowance');
            $ho = mod_num($r, 'housing_allowance'); $oa = mod_num($r, 'other_allowance');
            $od = mod_num($r, 'other_deductions'); $relief = mod_num($r, 'tax_relief');
            $exempt = in_array(strtolower((string) mod_val($r, 'ssnit_exempt')), ['1','yes','true','y'], true) ? 1 : 0;
            $sid = (int) $staff['id'];
            $stmt = $conn->prepare("INSERT INTO payroll_staff_pay
                (staff_id, basic_salary, transport_allowance, housing_allowance, other_allowance, other_deductions, tax_relief, ssnit_exempt)
                VALUES (?,?,?,?,?,?,?,?)
                ON DUPLICATE KEY UPDATE basic_salary=VALUES(basic_salary), transport_allowance=VALUES(transport_allowance),
                 housing_allowance=VALUES(housing_allowance), other_allowance=VALUES(other_allowance),
                 other_deductions=VALUES(other_deductions), tax_relief=VALUES(tax_relief), ssnit_exempt=VALUES(ssnit_exempt)");
            $stmt->bind_param('iddddddi', $sid, $basic, $tr, $ho, $oa, $od, $relief, $exempt);
            if ($stmt->execute()) $count++;
            $stmt->close();
        }
        fclose($h);
        return $count;
    }

    function importStudentHealth(string $file, mysqli $conn): int
    {
        health_ensure_tables($conn);
        $h = fopen($file, 'r'); if (!$h) return 0;
        $headers = fgetcsv($h); $count = 0;
        while (($row = fgetcsv($h)) !== false) {
            $r = array_combine($headers, $row);
            $stu = mod_resolve_student($conn, mod_val($r, 'student_id'));
            if (!$stu) continue;
            $sid = (int) $stu['id'];
            $blood = mod_val($r, 'blood_group'); $geno = mod_val($r, 'genotype');
            $allerg = mod_val($r, 'allergies'); $cond = mod_val($r, 'conditions'); $meds = mod_val($r, 'medications');
            $en = mod_val($r, 'emergency_name'); $ep = mod_val($r, 'emergency_phone'); $er = mod_val($r, 'emergency_relation');
            $ins = mod_val($r, 'insurance_no');
            $stmt = $conn->prepare("INSERT INTO student_health
                (student_id, blood_group, genotype, allergies, conditions, medications, emergency_name, emergency_phone, emergency_relation, insurance_no)
                VALUES (?,?,?,?,?,?,?,?,?,?)
                ON DUPLICATE KEY UPDATE blood_group=VALUES(blood_group), genotype=VALUES(genotype), allergies=VALUES(allergies),
                 conditions=VALUES(conditions), medications=VALUES(medications), emergency_name=VALUES(emergency_name),
                 emergency_phone=VALUES(emergency_phone), emergency_relation=VALUES(emergency_relation), insurance_no=VALUES(insurance_no)");
            $stmt->bind_param('isssssssss', $sid, $blood, $geno, $allerg, $cond, $meds, $en, $ep, $er, $ins);
            if ($stmt->execute()) $count++;
            $stmt->close();
        }
        fclose($h);
        return $count;
    }

    function importStudentLeadership(string $file, mysqli $conn): int
    {
        sa_ensure_tables($conn);
        $h = fopen($file, 'r'); if (!$h) return 0;
        $headers = fgetcsv($h); $count = 0;
        while (($row = fgetcsv($h)) !== false) {
            $r = array_combine($headers, $row);
            $stu = mod_resolve_student($conn, mod_val($r, 'student_id'));
            $roleT = mod_val($r, 'role'); $year = mod_val($r, 'academic_year');
            if (!$stu || !$roleT || !$year) continue;
            $sid = (int) $stu['id'];
            $term = mod_val($r, 'term'); $note = mod_val($r, 'note');
            $stmt = $conn->prepare("INSERT INTO student_leadership (student_id, role, academic_year, term, note) VALUES (?,?,?,?,?)");
            $stmt->bind_param('issss', $sid, $roleT, $year, $term, $note);
            if ($stmt->execute()) $count++;
            $stmt->close();
        }
        fclose($h);
        return $count;
    }

    function importStudentActivitiesCsv(string $file, mysqli $conn): int
    {
        sa_ensure_tables($conn);
        $h = fopen($file, 'r'); if (!$h) return 0;
        $headers = fgetcsv($h); $count = 0;
        while (($row = fgetcsv($h)) !== false) {
            $r = array_combine($headers, $row);
            $stu = mod_resolve_student($conn, mod_val($r, 'student_id'));
            $name = mod_val($r, 'activity_name'); $year = mod_val($r, 'academic_year');
            if (!$stu || !$name || !$year) continue;
            $type = strtolower((string) mod_val($r, 'activity_type'));
            if (!in_array($type, ['sport','club','society','other'], true)) $type = 'club';
            $sid = (int) $stu['id']; $pos = mod_val($r, 'position'); $ach = mod_val($r, 'achievement');
            $stmt = $conn->prepare("INSERT INTO student_activities (student_id, activity_name, activity_type, academic_year, position, achievement)
                                    VALUES (?,?,?,?,?,?)");
            $stmt->bind_param('isssss', $sid, $name, $type, $year, $pos, $ach);
            if ($stmt->execute()) $count++;
            $stmt->close();
        }
        fclose($h);
        return $count;
    }

    function importBiometricEnroll(string $file, mysqli $conn): int
    {
        biometric_ensure_tables($conn);
        $h = fopen($file, 'r'); if (!$h) return 0;
        $headers = fgetcsv($h); $count = 0;
        while (($row = fgetcsv($h)) !== false) {
            $r = array_combine($headers, $row);
            $ptype = strtolower((string) (mod_val($r, 'person_type') ?? 'student'));
            if (!in_array($ptype, ['student','staff'], true)) $ptype = 'student';
            $code = mod_val($r, 'person_code');
            $devUser = mod_val($r, 'device_user_id');
            if (!$code || !$devUser) continue;
            $person = ($ptype === 'staff') ? mod_resolve_staff($conn, $code) : mod_resolve_student($conn, $code);
            if (!$person) continue;
            $pid = (int) $person['id']; $pname = $person['name'];
            $stmt = $conn->prepare("INSERT INTO biometric_enrollments (person_type, person_id, person_name, method, device_user_id)
                                    VALUES (?,?,?, 'fingerprint', ?)");
            $stmt->bind_param('siss', $ptype, $pid, $pname, $devUser);
            if ($stmt->execute()) $count++;
            $stmt->close();
        }
        fclose($h);
        return $count;
    }
}
