<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: Senarai_Kakitangan.php');
    exit();
}

$staff_id = (int) ($_POST['staff_id'] ?? 0);
$agency_type = $_POST['agency_type'] ?? '';
$name = trim($_POST['name'] ?? '');
$position = trim($_POST['position'] ?? '');
$department = trim($_POST['department'] ?? '');
$agency = trim($_POST['agency'] ?? '');
$address = trim($_POST['address'] ?? '');

// Validation
if ($staff_id <= 0) {
    header('Location: Senarai_Kakitangan.php?error=invalid_id');
    exit();
}

if (empty($agency_type) || !in_array($agency_type, ['MAINPP', 'AGENSI LUAR'], true)) {
    header('Location: Senarai_Kakitangan.php?error=invalid_agency_type');
    exit();
}

if (empty($position)) {
    header('Location: Senarai_Kakitangan.php?error=empty_position');
    exit();
}

if ($agency_type === 'MAINPP' && empty($department)) {
    header('Location: Senarai_Kakitangan.php?error=empty_department');
    exit();
}

if ($agency_type === 'AGENSI LUAR') {
    if (empty($agency)) {
        header('Location: Senarai_Kakitangan.php?error=empty_agency');
        exit();
    }
    if (empty($address)) {
        header('Location: Senarai_Kakitangan.php?error=empty_address');
        exit();
    }
}

// Convert empty optional fields to '-'
if (empty($name)) {
    $name = '-';
}
if (empty($department)) {
    $department = '-';
}

$current_user_id = (int) ($_SESSION['user_id'] ?? 0);

// Check if staff exists
$check_stmt = mysqli_prepare($conn, "SELECT id, name, agency_type, source, user_id FROM staff_distribution_list WHERE id = ? AND deleted_at IS NULL");
if (!$check_stmt) {
    header('Location: Senarai_Kakitangan.php?error=db_error');
    exit();
}

mysqli_stmt_bind_param($check_stmt, "i", $staff_id);
mysqli_stmt_execute($check_stmt);
$check_result = mysqli_stmt_get_result($check_stmt);
$existing_staff = mysqli_fetch_assoc($check_result);

if (!$existing_staff) {
    header('Location: Senarai_Kakitangan.php?error=not_found');
    exit();
}

$source = 'MANUAL';
if ($agency_type === 'MAINPP' && (int) ($existing_staff['user_id'] ?? 0) > 0) {
    $source = 'USER_LIST';
}

// Update database
$stmt = mysqli_prepare($conn, "UPDATE staff_distribution_list SET agency_type = ?, name = ?, position = ?, department = ?, agency = ?, address = ?, source = ?, updated_by = ? WHERE id = ?");
if (!$stmt) {
    header('Location: Senarai_Kakitangan.php?error=db_error');
    exit();
}

mysqli_stmt_bind_param($stmt, "sssssssii", $agency_type, $name, $position, $department, $agency, $address, $source, $current_user_id, $staff_id);

if (mysqli_stmt_execute($stmt)) {
    logActivity(
        $conn,
        $current_user_id,
        'update_staff',
        'Kemaskini kakitangan: ' . $name . ' (ID: ' . $staff_id . ', Agensi: ' . $agency_type . ')'
    );
    header('Location: Senarai_Kakitangan.php?success=updated');
    exit();
} else {
    header('Location: Senarai_Kakitangan.php?error=update_failed');
    exit();
}
