<?php
/**
 * Salary Register AJAX Handler
 * Handles employee search, add, and auto-save
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

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

$db = getDB();
$siteId = getCurrentSiteId();
$action = $_REQUEST['action'] ?? '';

try {
    switch ($action) {
        case 'search_employee':
            $query = $_GET['q'] ?? '';
            $searchSiteId = $_GET['site_id'] ?? $siteId;
            
            if (strlen($query) < 2) {
                echo json_encode([]);
                exit;
            }
            
            $stmt = $db->prepare("
                SELECT 
                    e.employee_id,
                    e.employee_code,
                    CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
                    d.designation_name,
                    e.employment_status,
                    ems.category,
                    ems.basic_salary,
                    ems.hra,
                    ems.special_allowance,
                    ems.other_allowance
                FROM employees e
                LEFT JOIN designations d ON e.designation_id = d.designation_id
                LEFT JOIN employee_master_sheet ems ON e.employee_id = ems.employee_id
                WHERE e.site_id = ? 
                  AND e.employment_status = 'active'
                  AND (
                      e.employee_code LIKE ? 
                      OR e.first_name LIKE ? 
                      OR e.last_name LIKE ?
                      OR CONCAT(e.first_name, ' ', e.last_name) LIKE ?
                  )
                LIMIT 10
            ");
            
            $searchTerm = "%{$query}%";
            $stmt->execute([$searchSiteId, $searchTerm, $searchTerm, $searchTerm, $searchTerm]);
            $employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode($employees);
            break;
            
        case 'add_employee':
            $employeeId = $_POST['employee_id'] ?? 0;
            $siteId = $_POST['site_id'] ?? $siteId;
            $month = $_POST['month'] ?? date('n');
            $year = $_POST['year'] ?? date('Y');
            $daysInMonth = $_POST['days'] ?? 31;
            
            // Check if already exists
            $checkStmt = $db->prepare("
                SELECT register_id FROM salary_register 
                WHERE employee_id = ? AND site_id = ? AND salary_month = ? AND salary_year = ?
            ");
            $checkStmt->execute([$employeeId, $siteId, $month, $year]);
            
            if ($checkStmt->fetch()) {
                echo json_encode(['success' => false, 'message' => 'Employee already added for this month']);
                exit;
            }
            
            // Get employee details
            $empStmt = $db->prepare("
                SELECT 
                    e.*,
                    CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
                    d.designation_name,
                    ems.category,
                    ems.basic_salary,
                    ems.hra,
                    ems.special_allowance,
                    ems.other_allowance
                FROM employees e
                LEFT JOIN designations d ON e.designation_id = d.designation_id
                LEFT JOIN employee_master_sheet ems ON e.employee_id = ems.employee_id
                WHERE e.employee_id = ?
            ");
            $empStmt->execute([$employeeId]);
            $employee = $empStmt->fetch();
            
            if (!$employee) {
                echo json_encode(['success' => false, 'message' => 'Employee not found']);
                exit;
            }
            
            // Get next sl_no
            $slNoStmt = $db->prepare("
                SELECT COALESCE(MAX(sl_no), 0) + 1 as next_sl 
                FROM salary_register 
                WHERE site_id = ? AND salary_month = ? AND salary_year = ?
            ");
            $slNoStmt->execute([$siteId, $month, $year]);
            $nextSlNo = $slNoStmt->fetch()['next_sl'];
            
            // Default values
            $basic = $employee['basic_salary'] ?? 15000;
            $vda = 0;
            $specialAllowance = $employee['special_allowance'] ?? 0;
            $otherAllowance = $employee['other_allowance'] ?? 3000;
            $hra = $employee['hra'] ?? 0;
            
            $presentDays = 0;
            $absentDays = 0;
            $weeklyOff = 0;
            $payDays = 0;
            
            // Calculations
            $totalEarningStructure = $basic + $vda + $specialAllowance + $otherAllowance + $hra;
            $earnedBasic = ($basic / $daysInMonth) * $payDays;
            $earnedHra = ($hra / $daysInMonth) * $payDays;
            $earnedOther = ($otherAllowance / $daysInMonth) * $payDays;
            $earnedSpl = ($specialAllowance / $daysInMonth) * $payDays;
            $totalEarning = $earnedBasic + $earnedHra + $earnedOther + $earnedSpl + $vda;
            
            $pf = $earnedBasic * 0.12;
            $esi = $totalEarning * 0.0075;
            $pt = 125;
            $totalDeduction = $pf + $esi + $pt;
            $netSalary = $totalEarning - $totalDeduction;
            
            $rebillPf = $earnedBasic * 0.12;
            $rebillEsic = $totalEarning * 0.0325;
            $rebillTotal = $rebillPf + $rebillEsic;
            $earnedCtc = $totalEarning + $rebillTotal;
            $perDayWages = $totalEarningStructure / $daysInMonth;
            
            // Insert record
            $insertStmt = $db->prepare("
                INSERT INTO salary_register (
                    site_id, employee_id, salary_month, salary_year, sl_no,
                    employee_type, category, status,
                    basic_salary, vda, special_allowance, other_allowance, hra, total_earning_structure,
                    present_days, absent_days, weekly_off, pay_days,
                    earned_basic, earned_hra, earned_other, earned_spl, total_earning,
                    pf, esi, pt, total_deduction, net_salary,
                    rebill_pf, rebill_esic, rebill_leave, rebill_holiday, rebill_bonus,
                    rebill_uniform, rebill_gratuity, rebill_food, rebill_total,
                    earned_ctc, per_day_wages, created_at
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW()
                )
            ");
            
            $insertStmt->execute([
                $siteId, $employeeId, $month, $year, $nextSlNo,
                'FTC', $employee['category'] ?? 'Skilled', 'Active',
                $basic, $vda, $specialAllowance, $otherAllowance, $hra, $totalEarningStructure,
                $presentDays, $absentDays, $weeklyOff, $payDays,
                $earnedBasic, $earnedHra, $earnedOther, $earnedSpl, $totalEarning,
                $pf, $esi, $pt, $totalDeduction, $netSalary,
                $rebillPf, $rebillEsic, 0, 0, 0, 0, 0, 0, $rebillTotal,
                $earnedCtc, $perDayWages
            ]);
            
            echo json_encode(['success' => true, 'message' => 'Employee added successfully']);
            break;
            
        case 'save_row':
            $registerId = $_POST['register_id'] ?? 0;
            
            if (!$registerId) {
                echo json_encode(['success' => false, 'message' => 'Invalid register ID']);
                exit;
            }
            
            // Update record with all fields
            $updateStmt = $db->prepare("
                UPDATE salary_register SET
                    basic_salary = ?, vda = ?, special_allowance = ?, 
                    other_allowance = ?, hra = ?, total_earning_structure = ?,
                    present_days = ?, absent_days = ?, weekly_off = ?, pay_days = ?,
                    earned_basic = ?, earned_hra = ?, earned_other = ?, earned_spl = ?, total_earning = ?,
                    pf = ?, esi = ?, pt = ?, total_deduction = ?, net_salary = ?,
                    rebill_pf = ?, rebill_esic = ?, rebill_leave = ?, rebill_holiday = ?,
                    rebill_bonus = ?, rebill_uniform = ?, rebill_gratuity = ?, rebill_food = ?,
                    rebill_total = ?, earned_ctc = ?, per_day_wages = ?,
                    updated_at = NOW()
                WHERE register_id = ? AND site_id = ?
            ");
            
            $updateStmt->execute([
                $_POST['basic_salary'] ?? 0,
                $_POST['vda'] ?? 0,
                $_POST['special_allowance'] ?? 0,
                $_POST['other_allowance'] ?? 0,
                $_POST['hra'] ?? 0,
                $_POST['total_earning_structure'] ?? 0,
                $_POST['present_days'] ?? 0,
                $_POST['absent_days'] ?? 0,
                $_POST['weekly_off'] ?? 0,
                $_POST['pay_days'] ?? 0,
                $_POST['earned_basic'] ?? 0,
                $_POST['earned_hra'] ?? 0,
                $_POST['earned_other'] ?? 0,
                $_POST['earned_spl'] ?? 0,
                $_POST['total_earning'] ?? 0,
                $_POST['pf'] ?? 0,
                $_POST['esi'] ?? 0,
                $_POST['pt'] ?? 0,
                $_POST['total_deduction'] ?? 0,
                $_POST['net_salary'] ?? 0,
                $_POST['rebill_pf'] ?? 0,
                $_POST['rebill_esic'] ?? 0,
                $_POST['rebill_leave'] ?? 0,
                $_POST['rebill_holiday'] ?? 0,
                $_POST['rebill_bonus'] ?? 0,
                $_POST['rebill_uniform'] ?? 0,
                $_POST['rebill_gratuity'] ?? 0,
                $_POST['rebill_food'] ?? 0,
                $_POST['rebill_total'] ?? 0,
                $_POST['earned_ctc'] ?? 0,
                $_POST['per_day_wages'] ?? 0,
                $registerId,
                $siteId
            ]);
            
            echo json_encode(['success' => true, 'message' => 'Data saved successfully']);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
