<?php
ob_start();
include '../../includes/header.php';
require_once __DIR__ . '/_module.php';
require_once __DIR__ . '/../../classes/Branch.php';

payrollRequireAdmin($auth);

$payroll = new Payroll($conn);
$branchObj = new Branch($conn);
$branches = $branchObj->getAllBranches();
$branchRows = $branches->fetchAll(PDO::FETCH_ASSOC);
$departments = $payroll->getDepartments();
$grades = $payroll->getSalaryGrade();
$error = '';

$employeeId = (int)($_GET['id'] ?? $_POST['employee_id'] ?? 0);
if ($employeeId <= 0) {
    header('Location: employee_list.php');
    exit();
}

$employee = $payroll->getEmployeeById($employeeId);
if (!$employee) {
    header('Location: employee_list.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [
        'employee_code'             => trim($_POST['employee_code'] ?? ''),
        'employee_fullname'         => trim($_POST['employee_fullname'] ?? ''),
        'preferred_name'            => trim($_POST['preferred_name'] ?? ''),
        'date_of_birth'             => trim($_POST['date_of_birth'] ?? ''),
        'gender'                    => trim($_POST['gender'] ?? ''),
        'marital_status'            => trim($_POST['marital_status'] ?? ''),
        'employee_phone'            => trim($_POST['employee_phone'] ?? ''),
        'email'                     => trim($_POST['email'] ?? ''),
        'home_district'             => trim($_POST['home_district'] ?? ''),
        'ta'                        => trim($_POST['ta'] ?? ''),
        'village'                   => trim($_POST['village'] ?? ''),
        'place_of_residence'        => trim($_POST['place_of_residence'] ?? ''),
        'national_id'               => trim($_POST['national_id'] ?? ''),
        'tax_identification_number' => trim($_POST['tax_identification_number'] ?? ''),
        'social_security_number'    => trim($_POST['social_security_number'] ?? ''),
        'highest_qualification'     => trim($_POST['highest_qualification'] ?? ''),
        'next_of_kin_fullname'      => trim($_POST['next_of_kin_fullname'] ?? ''),
        'next_of_kin_phone'         => trim($_POST['next_of_kin_phone'] ?? ''),
        'next_of_kin_address'       => trim($_POST['next_of_kin_address'] ?? ''),
        'branch'                    => trim($_POST['branch'] ?? ''),
        'department_id'             => trim($_POST['department_id'] ?? ''),
        'employee_position'         => trim($_POST['employee_position'] ?? ''),
        'employment_type'           => trim($_POST['employment_type'] ?? 'permanent'),
        'employment_status'         => trim($_POST['employment_status'] ?? 'active'),
        'work_location'             => trim($_POST['work_location'] ?? ''),
        'contract_start'            => trim($_POST['contract_start'] ?? ''),
        'probation_end_date'        => trim($_POST['probation_end_date'] ?? ''),
        'contract_ends'             => trim($_POST['contract_ends'] ?? ''),
        'payment_frequency'         => trim($_POST['payment_frequency'] ?? 'Monthly'),
        'basic_salary'              => (float)($_POST['basic_salary'] ?? 0),
        'salary_grade_id'           => trim($_POST['salary_grade_id'] ?? ''),
        'currency_code'             => trim($_POST['currency_code'] ?? 'MWK'),
        'bank_details'              => trim($_POST['bank_details'] ?? ''),
        'bank_name'                 => trim($_POST['bank_name'] ?? ''),
        'bank_account_name'         => trim($_POST['bank_account_name'] ?? ''),
        'bank_account_number'       => trim($_POST['bank_account_number'] ?? ''),
        'bank_branch'               => trim($_POST['bank_branch'] ?? ''),
    ];

    $missingFields = [];
    $requiredFields = [
        'employee_fullname'  => 'Legal full name',
        'date_of_birth'      => 'Date of birth',
        'gender'             => 'Gender',
        'employee_phone'     => 'Phone',
        'national_id'        => 'National ID',
        'next_of_kin_fullname' => 'Next of kin name',
        'next_of_kin_phone'  => 'Next of kin phone',
        'next_of_kin_address' => 'Next of kin address',
        'branch'             => 'Branch',
        'employee_position'  => 'Position',
        'employment_type'    => 'Employment type',
        'employment_status'  => 'Employment status',
        'work_location'      => 'Work location',
        'contract_start'     => 'Start date',
        'payment_frequency'  => 'Pay frequency',
        'currency_code'      => 'Currency',
        'bank_name'          => 'Bank name',
        'bank_account_name'  => 'Bank account name',
        'bank_account_number' => 'Bank account number',
        'bank_branch'        => 'Bank branch',
    ];

    foreach ($requiredFields as $field => $label) {
        if (($data[$field] ?? '') === '') {
            $missingFields[] = $label;
        }
    }

    if ($data['tax_identification_number'] === '' && $data['social_security_number'] === '') {
        $missingFields[] = 'Tax ID or Pension ID';
    }

    if ($data['basic_salary'] <= 0) {
        $missingFields[] = 'Basic salary';
    }

    if (!empty($missingFields)) {
        $error = 'Please complete required employee information: ' . implode(', ', $missingFields) . '.';
        $employee = array_merge($employee, $data);
    } elseif ($payroll->updateEmployeeFull($employeeId, $data)) {
        header('Location: employee_list.php?updated=1');
        exit();
    } else {
        $error = 'Failed to update employee. Please try again.';
        $employee = array_merge($employee, $data);
    }
}

$v = function (string $key) use ($employee): string {
    return htmlspecialchars((string)($employee[$key] ?? ''), ENT_QUOTES, 'UTF-8');
};

payrollModuleStyles();
?>

<div class="container-fluid px-4">
    <?php payrollModuleNav('employees'); ?>

    <div class="payroll-page-head">
        <div>
            <h1>Edit Employee</h1>
            <p>Update identity, emergency contact, employment, payroll, and bank details for <?php echo $v('employee_fullname'); ?>.</p>
        </div>
        <a href="employee_list.php" class="btn btn-outline-secondary no-print"><i class="fas fa-arrow-left"></i> Back to Employees</a>
    </div>

    <?php payrollMigrationNotice($payroll, ['hr_departments'], 'Department and extended statutory fields become available after the professional schema upgrade.'); ?>

    <?php if ($error): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <form method="POST" class="payroll-panel">
        <input type="hidden" name="employee_id" value="<?php echo $employeeId; ?>">

        <div class="payroll-panel-title"><h2>Identity & Contact</h2></div>
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label" for="employee_code">Employee Code</label>
                <input type="text" class="form-control" id="employee_code" name="employee_code" value="<?php echo $v('employee_code'); ?>">
            </div>
            <div class="col-md-5">
                <label class="form-label" for="employee_fullname">Legal Full Name</label>
                <input type="text" class="form-control" id="employee_fullname" name="employee_fullname" value="<?php echo $v('employee_fullname'); ?>" required>
            </div>
            <div class="col-md-4">
                <label class="form-label" for="preferred_name">Preferred Name</label>
                <input type="text" class="form-control" id="preferred_name" name="preferred_name" value="<?php echo $v('preferred_name'); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" for="date_of_birth">Date of Birth</label>
                <input type="date" class="form-control" id="date_of_birth" name="date_of_birth" value="<?php echo $v('date_of_birth'); ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="gender">Gender</label>
                <select class="form-control" id="gender" name="gender" required>
                    <option value="">Select</option>
                    <?php foreach (['female' => 'Female', 'male' => 'Male', 'other' => 'Other', 'prefer_not_to_say' => 'Prefer not to say'] as $val => $lbl): ?>
                        <option value="<?php echo $val; ?>"<?php echo ($employee['gender'] ?? '') === $val ? ' selected' : ''; ?>><?php echo $lbl; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="marital_status">Marital Status</label>
                <select class="form-control" id="marital_status" name="marital_status">
                    <option value="">Select</option>
                    <?php foreach (['single' => 'Single', 'married' => 'Married', 'divorced' => 'Divorced', 'widowed' => 'Widowed'] as $val => $lbl): ?>
                        <option value="<?php echo $val; ?>"<?php echo ($employee['marital_status'] ?? '') === $val ? ' selected' : ''; ?>><?php echo $lbl; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="employee_phone">Phone</label>
                <input type="text" class="form-control" id="employee_phone" name="employee_phone" value="<?php echo $v('employee_phone'); ?>" required>
            </div>
            <div class="col-md-6">
                <label class="form-label" for="email">Email</label>
                <input type="email" class="form-control" id="email" name="email" value="<?php echo $v('email'); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" for="national_id">National ID</label>
                <input type="text" class="form-control" id="national_id" name="national_id" value="<?php echo $v('national_id'); ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="tax_identification_number">Tax ID</label>
                <input type="text" class="form-control" id="tax_identification_number" name="tax_identification_number" value="<?php echo $v('tax_identification_number'); ?>" aria-describedby="statutoryIdHelp">
            </div>
            <div class="col-md-3">
                <label class="form-label" for="social_security_number">Pension ID</label>
                <input type="text" class="form-control" id="social_security_number" name="social_security_number" value="<?php echo $v('social_security_number'); ?>" aria-describedby="statutoryIdHelp">
                <small id="statutoryIdHelp" class="form-text text-muted">Enter at least Tax ID or Pension ID.</small>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="highest_qualification">Highest Qualification</label>
                <input type="text" class="form-control" id="highest_qualification" name="highest_qualification" value="<?php echo $v('highest_qualification'); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" for="home_district">Home District</label>
                <input type="text" class="form-control" id="home_district" name="home_district" value="<?php echo $v('home_district'); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" for="ta">Traditional Authority</label>
                <input type="text" class="form-control" id="ta" name="ta" value="<?php echo $v('ta'); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" for="village">Village</label>
                <input type="text" class="form-control" id="village" name="village" value="<?php echo $v('village'); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" for="place_of_residence">Current Residence</label>
                <input type="text" class="form-control" id="place_of_residence" name="place_of_residence" value="<?php echo $v('place_of_residence'); ?>">
            </div>
        </div>

        <hr>
        <div class="payroll-panel-title"><h2>Emergency Contact</h2></div>
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label" for="next_of_kin_fullname">Next of Kin Name</label>
                <input type="text" class="form-control" id="next_of_kin_fullname" name="next_of_kin_fullname" value="<?php echo $v('next_of_kin_fullname'); ?>" required>
            </div>
            <div class="col-md-4">
                <label class="form-label" for="next_of_kin_phone">Next of Kin Phone</label>
                <input type="text" class="form-control" id="next_of_kin_phone" name="next_of_kin_phone" value="<?php echo $v('next_of_kin_phone'); ?>" required>
            </div>
            <div class="col-md-4">
                <label class="form-label" for="next_of_kin_address">Next of Kin Address</label>
                <input type="text" class="form-control" id="next_of_kin_address" name="next_of_kin_address" value="<?php echo $v('next_of_kin_address'); ?>" required>
            </div>
        </div>

        <hr>
        <div class="payroll-panel-title"><h2>Employment & Payroll</h2></div>
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label" for="branch">Branch</label>
                <select class="form-control" id="branch" name="branch" required>
                    <option value="">Select branch</option>
                    <?php foreach ($branchRows as $branch): ?>
                        <option value="<?php echo htmlspecialchars($branch['branch_id']); ?>"<?php echo (string)($employee['branch'] ?? '') === (string)$branch['branch_id'] ? ' selected' : ''; ?>><?php echo htmlspecialchars($branch['branch_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="department_id">Department</label>
                <select class="form-control" id="department_id" name="department_id">
                    <option value="">Not assigned</option>
                    <?php foreach ($departments as $department): ?>
                        <option value="<?php echo (int)$department['department_id']; ?>"<?php echo (string)($employee['department_id'] ?? '') === (string)$department['department_id'] ? ' selected' : ''; ?>><?php echo payrollText($department['department_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="employee_position">Position</label>
                <input type="text" class="form-control" id="employee_position" name="employee_position" value="<?php echo $v('employee_position'); ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="employment_type">Employment Type</label>
                <select class="form-control" id="employment_type" name="employment_type" required>
                    <?php foreach (['permanent' => 'Permanent', 'fixed_term' => 'Fixed Term', 'part_time' => 'Part Time', 'casual' => 'Casual', 'contractor' => 'Contractor'] as $val => $lbl): ?>
                        <option value="<?php echo $val; ?>"<?php echo ($employee['employment_type'] ?? '') === $val ? ' selected' : ''; ?>><?php echo $lbl; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="employment_status">Status</label>
                <select class="form-control" id="employment_status" name="employment_status" required>
                    <?php foreach (['active' => 'Active', 'probation' => 'Probation', 'suspended' => 'Suspended', 'terminated' => 'Terminated'] as $val => $lbl): ?>
                        <option value="<?php echo $val; ?>"<?php echo ($employee['employment_status'] ?? 'active') === $val ? ' selected' : ''; ?>><?php echo $lbl; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="work_location">Work Location</label>
                <select class="form-control" id="work_location" name="work_location" required>
                    <option value="">Select work location</option>
                    <?php foreach ($branchRows as $branch): ?>
                        <option value="<?php echo htmlspecialchars($branch['branch_name']); ?>"<?php echo ($employee['work_location'] ?? '') === $branch['branch_name'] ? ' selected' : ''; ?>><?php echo htmlspecialchars($branch['branch_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="contract_start">Start Date</label>
                <input type="date" class="form-control" id="contract_start" name="contract_start" value="<?php echo $v('contract_start'); ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="probation_end_date">Probation End</label>
                <input type="date" class="form-control" id="probation_end_date" name="probation_end_date" value="<?php echo $v('probation_end_date'); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" for="contract_ends">Contract End</label>
                <input type="date" class="form-control" id="contract_ends" name="contract_ends" value="<?php echo $v('contract_ends'); ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label" for="payment_frequency">Pay Frequency</label>
                <select class="form-control" id="payment_frequency" name="payment_frequency" required>
                    <?php foreach (['Monthly', 'Fortnight', 'Weekly', 'Daily'] as $freq): ?>
                        <option value="<?php echo $freq; ?>"<?php echo ($employee['payment_frequency'] ?? 'Monthly') === $freq ? ' selected' : ''; ?>><?php echo $freq; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="basic_salary">Basic Salary</label>
                <input type="number" step="0.01" min="0.01" class="form-control" id="basic_salary" name="basic_salary" value="<?php echo $v('basic_salary'); ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="salary_grade_id">Salary Grade</label>
                <select class="form-control" id="salary_grade_id" name="salary_grade_id">
                    <option value="">Not assigned</option>
                    <?php foreach ($grades as $grade): ?>
                        <option value="<?php echo (int)$grade['grade_id']; ?>"<?php echo (string)($employee['salary_grade_id'] ?? '') === (string)$grade['grade_id'] ? ' selected' : ''; ?>><?php echo payrollText($grade['grade_title']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="currency_code">Currency</label>
                <input type="text" class="form-control" id="currency_code" name="currency_code" value="<?php echo $v('currency_code') ?: 'MWK'; ?>" required>
            </div>
            <div class="col-12" id="grade_attributes_panel" style="display:none;">
                <div class="alert alert-info mb-0 p-2">
                    <strong id="grade_attr_title"></strong> — attributes applied from this grade:
                    <span class="ms-2" id="grade_attr_details"></span>
                </div>
            </div>
        </div>

        <script>
        (function () {
            var gradeData = <?php echo json_encode(array_column($grades, null, 'grade_id'), JSON_NUMERIC_CHECK); ?>;

            function formatPct(val) {
                return parseFloat(val) > 0 ? parseFloat(val).toFixed(2) + '%' : null;
            }

            function showGradeAttributes(gradeId) {
                var panel = document.getElementById('grade_attributes_panel');
                if (!gradeId || !gradeData[gradeId]) {
                    panel.style.display = 'none';
                    return;
                }
                var g = gradeData[gradeId];
                var parts = [];
                if (formatPct(g.pension))           parts.push('Pension: '    + formatPct(g.pension));
                if (formatPct(g.health_insurance))  parts.push('Health: '     + formatPct(g.health_insurance));
                if (formatPct(g.house_allowance))   parts.push('Housing: '    + formatPct(g.house_allowance));
                if (formatPct(g.overtime))          parts.push('Overtime: '   + formatPct(g.overtime));
                if (formatPct(g.other))             parts.push('Other: '      + formatPct(g.other));
                if (formatPct(g.tax_rate))          parts.push('Tax: '        + formatPct(g.tax_rate));

                document.getElementById('grade_attr_title').textContent = g.grade_title;
                document.getElementById('grade_attr_details').textContent = parts.length ? parts.join(' | ') : 'No additional rates set.';
                panel.style.display = 'block';
            }

            function applyGrade(gradeId, fillFields) {
                if (!gradeId || !gradeData[gradeId]) {
                    document.getElementById('grade_attributes_panel').style.display = 'none';
                    return;
                }
                var g = gradeData[gradeId];

                if (fillFields) {
                    document.getElementById('basic_salary').value = parseFloat(g.basic_salary || 0).toFixed(2);

                    var freqSelect = document.getElementById('payment_frequency');
                    for (var i = 0; i < freqSelect.options.length; i++) {
                        if (freqSelect.options[i].value === g.pay_frequency) {
                            freqSelect.selectedIndex = i;
                            break;
                        }
                    }

                    if (g.currency_code) {
                        document.getElementById('currency_code').value = g.currency_code;
                    }
                }

                showGradeAttributes(gradeId);
            }

            document.getElementById('salary_grade_id').addEventListener('change', function () {
                applyGrade(this.value, true);
            });

            // Show attributes on load for the currently assigned grade (without overwriting saved values)
            var currentGradeId = <?php echo (int)($employee['salary_grade_id'] ?? 0); ?>;
            if (currentGradeId) {
                showGradeAttributes(currentGradeId);
            }
        })();
        </script>

        <hr>
        <div class="payroll-panel-title"><h2>Bank Payment Details</h2></div>
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label" for="bank_name">Bank Name</label>
                <input type="text" class="form-control" id="bank_name" name="bank_name" value="<?php echo $v('bank_name'); ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="bank_account_name">Account Name</label>
                <input type="text" class="form-control" id="bank_account_name" name="bank_account_name" value="<?php echo $v('bank_account_name'); ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="bank_account_number">Account Number</label>
                <input type="text" class="form-control" id="bank_account_number" name="bank_account_number" value="<?php echo $v('bank_account_number'); ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label" for="bank_branch">Bank Branch</label>
                <input type="text" class="form-control" id="bank_branch" name="bank_branch" value="<?php echo $v('bank_branch'); ?>" required>
            </div>
            <div class="col-12">
                <label class="form-label" for="bank_details">Bank Details</label>
                <textarea class="form-control" id="bank_details" name="bank_details" rows="2"><?php echo $v('bank_details'); ?></textarea>
            </div>
        </div>

        <div class="mt-4">
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Changes</button>
            <a href="employee_list.php" class="btn btn-outline-secondary">Cancel</a>
        </div>
    </form>

    <?php payrollModuleEnd(); ?>
</div>

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