<?php
require_once '../includes/auth.php';
require_once '../includes/db.php';

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

if (!isLoggedIn() || !hasRole(['owner', 'admin', 'manager', 'supervisor', 'finance executive'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Handle both JSON and Multipart data
$data = json_decode(file_get_contents('php://input'), true);
$action = $_POST['action'] ?? $data['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'get_next_code':
        try {
            $nextId = 1;
            $row = fetch("SHOW TABLE STATUS LIKE 'employees'");
            if ($row && isset($row['Auto_increment'])) {
                $nextId = intval($row['Auto_increment']);
            } else {
                $maxRow = fetch("SELECT MAX(id) as max_id FROM employees");
                if ($maxRow && isset($maxRow['max_id'])) {
                    $nextId = intval($maxRow['max_id']) + 1;
                }
            }
            $nextCode = 'EMP-' . str_pad($nextId, 5, '0', STR_PAD_LEFT);
            echo json_encode(['success' => true, 'employee_code' => $nextCode]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        exit;

    case 'save':
        // If multipart, data comes from $_POST
        $emp = isset($_POST['name']) ? $_POST : $data['employee'];
        $id = $emp['id'] ?? '';
        $company_id = $_SESSION['company_id'];
        $branch_id = $emp['branch_id'] ?? null;
        
        if (empty($emp['reporting_manager_id'])) {
            echo json_encode(['success' => false, 'message' => 'Reporting Manager is required. Please select one.']);
            exit;
        }

        $username = trim($emp['username'] ?? '');
        if (empty($id)) {
            if (empty($username)) {
                echo json_encode(['success' => false, 'message' => 'Username is required for login credentials.']);
                exit;
            }
            if (empty($emp['password'])) {
                echo json_encode(['success' => false, 'message' => 'Password is required for login credentials.']);
                exit;
            }
            
            $dup = fetch("SELECT id FROM users WHERE username = ?", [$username]);
            if ($dup) {
                echo json_encode(['success' => false, 'message' => 'Username already exists. Please choose a different username.']);
                exit;
            }
        } else {
            if (empty($username)) {
                echo json_encode(['success' => false, 'message' => 'Username is required.']);
                exit;
            }
            $existingUser = fetch("SELECT user_id FROM employees WHERE id = ? AND company_id = ?", [$id, $company_id]);
            $userId = $existingUser['user_id'] ?? null;
            if ($userId) {
                $dup = fetch("SELECT id FROM users WHERE username = ? AND id != ?", [$username, $userId]);
                if ($dup) {
                    echo json_encode(['success' => false, 'message' => 'Username already exists. Please choose a different username.']);
                    exit;
                }
            } else {
                $dup = fetch("SELECT id FROM users WHERE username = ?", [$username]);
                if ($dup) {
                    echo json_encode(['success' => false, 'message' => 'Username already exists. Please choose a different username.']);
                    exit;
                }
            }
        }
        
        try {
            global $pdo;
            $pdo->beginTransaction();
            
            // Handle Profile Picture Upload
            $profile_picture = null;
            if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === 0) {
                $upload_dir = '../uploads/employees/';
                if (!file_exists($upload_dir)) mkdir($upload_dir, 0777, true);
                
                $file_ext = pathinfo($_FILES['profile_picture']['name'], PATHINFO_EXTENSION);
                $file_name = 'emp_' . time() . '_' . uniqid() . '.' . $file_ext;
                $upload_path = $upload_dir . $file_name;
                
                if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $upload_path)) {
                    $profile_picture = 'uploads/employees/' . $file_name;
                }
            }

            $userId = null;
            $reportingManagerId = !empty($emp['reporting_manager_id']) ? intval($emp['reporting_manager_id']) : null;
            if (!empty($emp['username'])) {
                $role = fetch("SELECT name FROM roles WHERE id = ?", [$emp['role_id']])['name'];
                $userRole = strtolower($role);
                
                $existingEmployee = $id ? fetch("SELECT user_id FROM employees WHERE id = ? AND company_id = ?", [$id, $company_id]) : null;
                $userId = $existingEmployee['user_id'] ?? null;
                
                if ($userId) {
                    if (!empty($emp['password'])) {
                        $sql = "UPDATE users SET name=?, username=?, role=?, dashboard_id=?, password=? WHERE id=? AND company_id=?";
                        query($sql, [$emp['name'], $emp['username'], $userRole, $emp['dashboard_id'], password_hash($emp['password'], PASSWORD_DEFAULT), $userId, $company_id]);
                    } else {
                        $sql = "UPDATE users SET name=?, username=?, role=?, dashboard_id=? WHERE id=? AND company_id=?";
                        query($sql, [$emp['name'], $emp['username'], $userRole, $emp['dashboard_id'], $userId, $company_id]);
                    }
                } else {
                    $sql = "INSERT INTO users (company_id, name, username, role, dashboard_id, password) VALUES (?, ?, ?, ?, ?, ?)";
                    query($sql, [$company_id, $emp['name'], $emp['username'], $userRole, $emp['dashboard_id'], password_hash($emp['password'] ?: '123456', PASSWORD_DEFAULT)]);
                    $userId = $pdo->lastInsertId();
                }
            }

            $employeeCodeInput = !empty($emp['employee_code']) ? trim($emp['employee_code']) : null;
            $shiftId = !empty($emp['shift_id']) ? intval($emp['shift_id']) : null;
            $baseSalary = floatval($emp['base_salary'] ?? 0);
            if ($id) {
                // Update Employee
                $hourlyRate = floatval($emp['hourly_rate'] ?? 0);
                if ($profile_picture) {
                    $sql = "UPDATE employees SET employee_code=?, name=?, email=?, phone=?, nic=?, address=?, hourly_rate=?, base_salary=?, role_id=?, dashboard_id=?, user_id=?, branch_id=?, profile_picture=?, reporting_manager_id=?, shift_id=? WHERE id=? AND company_id=?";
                    query($sql, [$employeeCodeInput, $emp['name'], $emp['email'], $emp['phone'], $emp['nic'], $emp['address'], $hourlyRate, $baseSalary, $emp['role_id'], $emp['dashboard_id'], $userId, $branch_id, $profile_picture, $reportingManagerId, $shiftId, $id, $company_id]);
                } else {
                    $sql = "UPDATE employees SET employee_code=?, name=?, email=?, phone=?, nic=?, address=?, hourly_rate=?, base_salary=?, role_id=?, dashboard_id=?, user_id=?, branch_id=?, reporting_manager_id=?, shift_id=? WHERE id=? AND company_id=?";
                    query($sql, [$employeeCodeInput, $emp['name'], $emp['email'], $emp['phone'], $emp['nic'], $emp['address'], $hourlyRate, $baseSalary, $emp['role_id'], $emp['dashboard_id'], $userId, $branch_id, $reportingManagerId, $shiftId, $id, $company_id]);
                }
                query("DELETE FROM employee_skill WHERE employee_id = ?", [$id]);
            } else {
                // Create Employee
                $hourlyRate = floatval($emp['hourly_rate'] ?? 0);
                $sql = "INSERT INTO employees (company_id, branch_id, name, email, phone, nic, address, hourly_rate, base_salary, role_id, dashboard_id, user_id, profile_picture, reporting_manager_id, employee_code, shift_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                query($sql, [$company_id, $branch_id, $emp['name'], $emp['email'], $emp['phone'], $emp['nic'], $emp['address'], $hourlyRate, $baseSalary, $emp['role_id'], $emp['dashboard_id'], $userId, $profile_picture, $reportingManagerId, $employeeCodeInput, $shiftId]);
                $id = $pdo->lastInsertId();
                if (empty($employeeCodeInput)) {
                    $employeeCode = 'EMP-' . str_pad($id, 5, '0', STR_PAD_LEFT);
                    query("UPDATE employees SET employee_code = ? WHERE id = ?", [$employeeCode, $id]);
                }
            }

            // Insert Skills
            $skills = isset($_POST['skills']) ? $_POST['skills'] : ($emp['skills'] ?? []);
            if (!empty($skills)) {
                foreach ($skills as $skillId) {
                    query("INSERT INTO employee_skill (employee_id, skill_id) VALUES (?, ?)", [$id, $skillId]);
                }
            }

            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'Employee record saved successfully']);
        } catch (Exception $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        break;

    case 'delete':
        $id = $_POST['id'] ?? $data['id'] ?? '';
        $company_id = $_SESSION['company_id'];
        $emp = fetch("SELECT user_id FROM employees WHERE id = ? AND company_id = ?", [$id, $company_id]);
        if ($emp) {
            if ($emp['user_id']) {
                query("DELETE FROM users WHERE id = ? AND company_id = ?", [$emp['user_id'], $company_id]);
            }
            query("DELETE FROM employee_skill WHERE employee_id = ?", [$id]);
            query("DELETE FROM employees WHERE id = ? AND company_id = ?", [$id, $company_id]);
            echo json_encode(['success' => true, 'message' => 'Employee deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Employee not found']);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
