<?php
// employee_add_script.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
session_write_close();

// 🔥 FORCE WEST AFRICA TIME (WAT) TO MATCH LOGS AND LOCAL TIME EXACTLY
date_default_timezone_set('Africa/Lagos');

require '../config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$userRole = strtolower(trim($_SESSION['role'] ?? ''));
if (!in_array($userRole, ['admin', 'superadmin','hr'])) {
    die("Access Denied");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. Extract Base Form Data
    $name           = trim($_POST['name'] ?? '');
    $dob            = !empty($_POST['dob']) ? $_POST['dob'] : null;
    $gender         = trim($_POST['gender'] ?? '');
    $marital_status = trim($_POST['marital_status'] ?? '');

    // Unified Next of Kin / Spouse Params
    $nok_name    = trim($_POST['nok_name'] ?? '');
    $nok_phone   = trim($_POST['nok_phone'] ?? '');
    $nok_address = trim($_POST['nok_address'] ?? '');
    
    $employee_no   = trim($_POST['employee_no'] ?? '');
    $department_id = intval($_POST['department_id'] ?? 0);
    $designation   = trim($_POST['designation'] ?? '');
    $position      = trim($_POST['position'] ?? '');
    $hire_date     = !empty($_POST['hire_date']) ? $_POST['hire_date'] : null;
    $is_manager    = isset($_POST['is_manager']) ? 1 : 0;

    // Geographic Anchors
    $country = trim($_POST['country'] ?? 'Nigeria');
    $state   = trim($_POST['state'] ?? '');
    $lga     = trim($_POST['lga'] ?? '');
    
    $email   = trim($_POST['email'] ?? '');
    $phone   = trim($_POST['phone'] ?? '');
    $address = trim($_POST['address'] ?? '');
    
    $bank_name    = trim($_POST['bank_name'] ?? '');
    $account_no   = trim($_POST['account_no'] ?? '');
    $account_name = trim($_POST['account_name'] ?? '');

    // Statutory / Pension Parameters
    $pfa_name    = trim($_POST['pfa_name'] ?? '');
    $pension_pin = trim($_POST['pension_pin'] ?? '');
    $nin         = trim($_POST['nin'] ?? '');

    // Medical Metrics Extraction
    $blood_group        = trim($_POST['blood_group'] ?? '');
    $genotype           = trim($_POST['genotype'] ?? '');
    $allergies          = trim($_POST['allergies'] ?? '');
    $medical_conditions = trim($_POST['medical_conditions'] ?? '');

    // Mandatory Field Enforcement Baseline
    if (empty($name) || empty($employee_no)) {
        header("Location: employee_add.php?error=empty_fields");
        exit;
    }

    // Check for duplicate Employee Identification Code
    $checkStmt = $conn->prepare("SELECT id FROM employees WHERE employee_no = ? LIMIT 1");
    $checkStmt->bind_param("s", $employee_no);
    $checkStmt->execute();
    $checkStmt->store_result();
    
    if ($checkStmt->num_rows > 0) {
        $checkStmt->close();
        header("Location: employee_add.php?error=duplicate_id");
        exit;
    }
    $checkStmt->close();

    // 2. Handle Profile Avatar Upload Stream
    $avatarPath = null;
    if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
        $avatarTmpName = $_FILES['avatar']['tmp_name'];
        $avatarOrigName = basename($_FILES['avatar']['name']);
        $avatarExt = strtolower(pathinfo($avatarOrigName, PATHINFO_EXTENSION));
        
        $avatarNewName = "avatar_" . time() . "_" . uniqid() . "." . $avatarExt;
        $avatarDir = "../uploads/avatars/";
        
        if (!is_dir($avatarDir)) {
            mkdir($avatarDir, 0755, true);
        }
        
        if (move_uploaded_file($avatarTmpName, $avatarDir . $avatarNewName)) {
            $avatarPath = "uploads/avatars/" . $avatarNewName;
        }
    }

    // 3. Main Transaction Pipeline Group Insertion (Updated: 30 fields total)
    $sql = "INSERT INTO employees (
                name, dob, gender, marital_status, nok_name, nok_phone, nok_address,
                employee_no, department_id, designation, position, hire_date, is_manager, 
                country, state, lga, email, phone, address, 
                bank_name, account_no, account_name, pfa_name, pension_pin, nin, 
                blood_group, genotype, allergies, medical_conditions, avatar
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    
    // Bind Definition Map updated to string type values for medical elements (30 options matching structural mapping parameters)
    $stmt->bind_param(
        "sssssssisssissssssssssssssssss", 
        $name, $dob, $gender, $marital_status, $nok_name, $nok_phone, $nok_address,
        $employee_no, $department_id, $designation, $position, $hire_date, $is_manager,
        $country, $state, $lga, $email, $phone, $address,
        $bank_name, $account_no, $account_name, $pfa_name, $pension_pin, $nin,
        $blood_group, $genotype, $allergies, $medical_conditions, $avatarPath
    );
    
    if ($stmt->execute()) {
        $newEmployeeId = $stmt->insert_id;
        $stmt->close();

        // 4. Relational Pipeline: Dynamic Multi-Document Processor Loop
        if (!empty($_POST['docs']) && isset($_FILES['doc_files'])) {
            $uploadedFiles = $_FILES['doc_files'];
            
            foreach ($_POST['docs'] as $index => $docMeta) {
                $docTitle  = trim($docMeta['title'] ?? '');
                $docExpiry = !empty($docMeta['expiry']) ? $docMeta['expiry'] : null;
                
                if (isset($uploadedFiles['name'][$index]) && $uploadedFiles['error'][$index] === UPLOAD_ERR_OK) {
                    $fileTmpName  = $uploadedFiles['tmp_name'][$index];
                    $fileOrigName = basename($uploadedFiles['name'][$index]);
                    $fileExt      = strtolower(pathinfo($fileOrigName, PATHINFO_EXTENSION));
                    
                    $fileNewName  = "doc_" . time() . "_" . uniqid() . "." . $fileExt;
                    $docDir       = "../uploads/documents/";
                    
                    if (!is_dir($docDir)) {
                        mkdir($docDir, 0755, true);
                    }
                    
                    if (move_uploaded_file($fileTmpName, $docDir . $fileNewName)) {
                        $savedDocPath = "uploads/documents/" . $fileNewName;
                        
                        $docSql = "INSERT INTO employee_documents (employee_id, title, file_path, expiry_date) VALUES (?, ?, ?, ?)";
                        $docStmt = $conn->prepare($docSql);
                        $docStmt->bind_param("isss", $newEmployeeId, $docTitle, $savedDocPath, $docExpiry);
                        $docStmt->execute();
                        $docStmt->close();
                    }
                }
            }
        }

        // 5. Relational Pipeline: Nested Educational Background Processor Loop
        if (!empty($_POST['education'])) {
            foreach ($_POST['education'] as $eduItem) {
                $institution   = trim($eduItem['institution'] ?? '');
                $qualification = trim($eduItem['qualification'] ?? '');
                $start_year    = intval($eduItem['start_year'] ?? 0);
                $end_year      = intval($eduItem['end_year'] ?? 0);

                if (!empty($institution) && !empty($qualification)) {
                    $eduSql = "INSERT INTO employee_education (employee_id, institution, qualification, start_year, end_year) VALUES (?, ?, ?, ?, ?)";
                    $eduStmt = $conn->prepare($eduSql);
                    $eduStmt->bind_param("issii", $newEmployeeId, $institution, $qualification, $start_year, $end_year);
                    $eduStmt->execute();
                    $eduStmt->close();
                }
            }
        }

        // Action routing pipeline completed successfully
        header("Location: employees.php?saved=1&new_id=" . $newEmployeeId);
    } else {
        $errorStr = urlencode($conn->error);
        $stmt->close();
        header("Location: employee_add.php?error=db_failure&details=" . $errorStr);
    }
    exit;
}