<?php
// employees/employee_edit_script.php
error_reporting(E_ALL);
ini_set('display_errors', 0);
session_start();
session_write_close();

date_default_timezone_set('Africa/Lagos');
header('Content-Type: application/json');

require '../config.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized session access.']);
    exit;
}

$userRole = strtolower(trim($_SESSION['role'] ?? ''));
if (!in_array($userRole, ['admin', 'superadmin','hr'])) {
    echo json_encode(['success' => false, 'message' => 'Access Denied: Permission tier missing.']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $employeeId = intval($_POST['id'] ?? 0);
    
    if ($employeeId <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid or missing employee primary target key.']);
        exit;
    }

    // 1. Mandatory Parameter Extraction
    $name        = trim($_POST['name'] ?? '');
    $employee_no = trim((string)($_POST['employee_no'] ?? ''));

    if (empty($name) || empty($employee_no)) {
        echo json_encode(['success' => false, 'message' => 'Primary parameters missing: Full Name and Employee ID Code are required.']);
        exit;
    }

    // Duplicate Check excluding current employee ID
    $checkStmt = $conn->prepare("SELECT id FROM employees WHERE employee_no = ? AND id != ? LIMIT 1");
    $checkStmt->bind_param("si", $employee_no, $employeeId);
    $checkStmt->execute();
    $checkStmt->store_result();
    if ($checkStmt->num_rows > 0) {
        $checkStmt->close();
        echo json_encode(['success' => false, 'message' => "Duplicate ID Code collision: '{$employee_no}' is already assigned to another employee."]);
        exit;
    }
    $checkStmt->close();

    // Fetch existing avatar for replacement handling
    $fetchCurr = $conn->prepare("SELECT avatar FROM employees WHERE id = ? LIMIT 1");
    $fetchCurr->bind_param("i", $employeeId);
    $fetchCurr->execute();
    $currentEmp = $fetchCurr->get_result()->fetch_assoc();
    $fetchCurr->close();

    // 2. Avatar File Upload Processing
    $avatarPath = $currentEmp['avatar'] ?? 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)) {
            if (!empty($currentEmp['avatar']) && file_exists("../" . $currentEmp['avatar'])) {
                @unlink("../" . $currentEmp['avatar']);
            }
            $avatarPath = "uploads/avatars/" . $avatarNewName;
        }
    }

    // 3. Dynamic Safe Query Assembly (Eliminates Positional Parameter Misalignment)
    $fields = [
        'name'               => ['type' => 's', 'value' => $name],
        'dob'                => ['type' => 's', 'value' => !empty($_POST['dob']) ? $_POST['dob'] : null],
        'gender'             => ['type' => 's', 'value' => trim($_POST['gender'] ?? '')],
        'marital_status'     => ['type' => 's', 'value' => trim($_POST['marital_status'] ?? '')],
        'nok_name'           => ['type' => 's', 'value' => trim($_POST['nok_name'] ?? '')],
        'nok_phone'          => ['type' => 's', 'value' => trim($_POST['nok_phone'] ?? '')],
        'nok_address'        => ['type' => 's', 'value' => trim($_POST['nok_address'] ?? '')],
        'employee_no'        => ['type' => 's', 'value' => $employee_no], // Forced string
        'department_id'      => ['type' => 'i', 'value' => intval($_POST['department_id'] ?? 0)],
        'designation'        => ['type' => 's', 'value' => trim($_POST['designation'] ?? '')],
        'position'           => ['type' => 's', 'value' => trim($_POST['position'] ?? '')],
        'hire_date'          => ['type' => 's', 'value' => !empty($_POST['hire_date']) ? $_POST['hire_date'] : null],
        'is_manager'         => ['type' => 'i', 'value' => isset($_POST['is_manager']) ? 1 : 0],
        'country'            => ['type' => 's', 'value' => trim($_POST['country'] ?? 'Nigeria')],
        'state'              => ['type' => 's', 'value' => trim($_POST['state'] ?? '')],
        'lga'                => ['type' => 's', 'value' => trim($_POST['lga'] ?? '')],
        'email'              => ['type' => 's', 'value' => trim($_POST['email'] ?? '')],
        'phone'              => ['type' => 's', 'value' => trim($_POST['phone'] ?? '')],
        'address'            => ['type' => 's', 'value' => trim($_POST['address'] ?? '')],
        'bank_name'          => ['type' => 's', 'value' => trim($_POST['bank_name'] ?? '')],
        'account_no'         => ['type' => 's', 'value' => trim($_POST['account_no'] ?? '')],
        'account_name'       => ['type' => 's', 'value' => trim($_POST['account_name'] ?? '')],
        'pfa_name'           => ['type' => 's', 'value' => trim($_POST['pfa_name'] ?? '')],
        'pension_pin'        => ['type' => 's', 'value' => trim($_POST['pension_pin'] ?? '')],
        'nin'                => ['type' => 's', 'value' => trim($_POST['nin'] ?? '')],
        'blood_group'        => ['type' => 's', 'value' => trim($_POST['blood_group'] ?? '')],
        'genotype'           => ['type' => 's', 'value' => trim($_POST['genotype'] ?? '')],
        'allergies'          => ['type' => 's', 'value' => trim($_POST['allergies'] ?? '')],
        'medical_conditions' => ['type' => 's', 'value' => trim($_POST['medical_conditions'] ?? '')],
        'avatar'             => ['type' => 's', 'value' => $avatarPath]
    ];

    $setClause = [];
    $typesStr  = "";
    $valuesArr = [];

    foreach ($fields as $col => $meta) {
        $setClause[] = "`{$col}` = ?";
        $typesStr   .= $meta['type'];
        $valuesArr[] = $meta['value'];
    }

    // Append ID for WHERE clause
    $typesStr  .= "i";
    $valuesArr[] = $employeeId;

    $sql = "UPDATE employees SET " . implode(', ', $setClause) . " WHERE id = ?";
    $stmt = $conn->prepare($sql);

    // Bind parameters dynamically by reference
    $bindParams = [$typesStr];
    for ($i = 0; $i < count($valuesArr); $i++) {
        $bindParams[] = &$valuesArr[$i];
    }
    
    call_user_func_array([$stmt, 'bind_param'], $bindParams);

    if (!$stmt->execute()) {
        $err = $stmt->error;
        $stmt->close();
        echo json_encode(['success' => false, 'message' => 'Database record update failed: ' . $err]);
        exit;
    }
    $stmt->close();

    // 4. Document Management
    if (!empty($_POST['deleted_docs'])) {
        foreach ($_POST['deleted_docs'] as $delDocId) {
            $delDocId = intval($delDocId);
            $getDoc = $conn->query("SELECT file_path FROM employee_documents WHERE id = {$delDocId} AND employee_id = {$employeeId}");
            if ($getDoc && $docRow = $getDoc->fetch_assoc()) {
                if (!empty($docRow['file_path']) && file_exists("../" . $docRow['file_path'])) {
                    @unlink("../" . $docRow['file_path']);
                }
                $conn->query("DELETE FROM employee_documents WHERE id = {$delDocId} AND employee_id = {$employeeId}");
            }
        }
    }

    if (!empty($_POST['existing_docs'])) {
        foreach ($_POST['existing_docs'] as $docId => $existingMeta) {
            $docId = intval($docId);
            $docTitle = trim($existingMeta['title'] ?? '');
            $docExpiry = !empty($existingMeta['expiry']) ? $existingMeta['expiry'] : null;

            $upDocStmt = $conn->prepare("UPDATE employee_documents SET title = ?, expiry_date = ? WHERE id = ? AND employee_id = ?");
            $upDocStmt->bind_param("ssii", $docTitle, $docExpiry, $docId, $employeeId);
            $upDocStmt->execute();
            $upDocStmt->close();
        }
    }

    if (!empty($_POST['new_docs']) && isset($_FILES['new_doc_files'])) {
        $newFiles = $_FILES['new_doc_files'];
        foreach ($_POST['new_docs'] as $index => $newMeta) {
            $docTitle = trim($newMeta['title'] ?? '');
            $docExpiry = !empty($newMeta['expiry']) ? $newMeta['expiry'] : null;

            if (isset($newFiles['name'][$index]) && $newFiles['error'][$index] === UPLOAD_ERR_OK) {
                $fileTmpName  = $newFiles['tmp_name'][$index];
                $fileOrigName = basename($newFiles['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;
                    $insDocStmt = $conn->prepare("INSERT INTO employee_documents (employee_id, title, file_path, expiry_date) VALUES (?, ?, ?, ?)");
                    $insDocStmt->bind_param("isss", $employeeId, $docTitle, $savedDocPath, $docExpiry);
                    $insDocStmt->execute();
                    $insDocStmt->close();
                }
            }
        }
    }

    // 5. Education History Sync
    if (isset($_POST['education'])) {
        $conn->query("DELETE FROM employee_education WHERE employee_id = {$employeeId}");
        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)) {
                $eduStmt = $conn->prepare("INSERT INTO employee_education (employee_id, institution, qualification, start_year, end_year) VALUES (?, ?, ?, ?, ?)");
                $eduStmt->bind_param("issii", $employeeId, $institution, $qualification, $start_year, $end_year);
                $eduStmt->execute();
                $eduStmt->close();
            }
        }
    }

    echo json_encode([
        'success' => true,
        'message' => 'Employee profile record updated successfully.'
    ]);
    exit;
}