<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../config.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }

if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized Access']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid Request Method']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);

$emp_id = $data['emp_id'] ?? '';
$name = trim($data['name'] ?? '');
$email = trim($data['email'] ?? '');
$mobile = trim($data['mobile'] ?? '');
$gender = $data['gender'] ?? 'Male';
$dob = !empty($data['dob']) ? $data['dob'] : null;
$blood_group = trim($data['blood_group'] ?? '');
$branch_id = !empty($data['branch_id']) ? $data['branch_id'] : null;
$department = trim($data['department'] ?? '');
$designation = trim($data['designation'] ?? '');
$employment_type = $data['employment_type'] ?? 'Permanent';
$role = $data['role'] ?? 'employee';
$password = !empty($data['password']) ? password_hash($data['password'], PASSWORD_DEFAULT) : '';

if (empty($name) || empty($email)) {
    echo json_encode(['success' => false, 'message' => 'Name and Email are strictly required.']);
    exit;
}

$db = getDB();

try {
    $db->beginTransaction();

    if ($emp_id) {
        // Edit Mode
        if ($password) {
            $stmt = $db->prepare("UPDATE employees SET name=?, email=?, mobile=?, gender=?, dob=?, blood_group=?, branch_id=?, department=?, designation=?, employment_type=?, role=?, password=? WHERE id=?");
            $stmt->execute([$name, $email, $mobile, $gender, $dob, $blood_group, $branch_id, $department, $designation, $employment_type, $role, $password, $emp_id]);
        } else {
            $stmt = $db->prepare("UPDATE employees SET name=?, email=?, mobile=?, gender=?, dob=?, blood_group=?, branch_id=?, department=?, designation=?, employment_type=?, role=? WHERE id=?");
            $stmt->execute([$name, $email, $mobile, $gender, $dob, $blood_group, $branch_id, $department, $designation, $employment_type, $role, $emp_id]);
        }
        $action = "Updated Employee {$name}";
    } else {
        // Add Mode
        if (empty($password)) {
            echo json_encode(['success' => false, 'message' => 'Initial password is required for new employees.']);
            exit;
        }
        $stmt = $db->prepare("INSERT INTO employees (name, email, mobile, gender, dob, blood_group, branch_id, department, designation, employment_type, role, password, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')");
        $stmt->execute([$name, $email, $mobile, $gender, $dob, $blood_group, $branch_id, $department, $designation, $employment_type, $role, $password]);
        $emp_id = $db->lastInsertId();
        
        // Auto-generate emp code if needed
        $emp_code = 'EMP-'.str_pad($emp_id, 4, '0', STR_PAD_LEFT);
        $db->prepare("UPDATE employees SET emp_code=? WHERE id=?")->execute([$emp_code, $emp_id]);
        
        $action = "Added New Employee {$emp_code}";
    }

    // Log the action
    $log = $db->prepare("INSERT INTO employee_activity_logs (employee_id, action, performed_by, ip_address) VALUES (?, ?, ?, ?)");
    $log->execute([$emp_id, $action, $_SESSION['admin_id'], $_SERVER['REMOTE_ADDR']]);

    $db->commit();
    echo json_encode(['success' => true, 'message' => 'Employee saved successfully']);

} catch (PDOException $e) {
    $db->rollBack();
    // Catch duplicate email error
    if ($e->getCode() == 23000) {
        echo json_encode(['success' => false, 'message' => 'Email already exists.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Database Error: ' . $e->getMessage()]);
    }
}
