<?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);
if ($staff_id > 0) {
    require __DIR__ . '/staff_update.php';
    exit();
}

$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 (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);

// Insert into database
$source = 'MANUAL'; // Manual entry
$stmt = mysqli_prepare($conn, "INSERT INTO staff_distribution_list (agency_type, name, position, department, agency, address, source, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
if (!$stmt) {
    header('Location: Senarai_Kakitangan.php?error=db_error');
    exit();
}

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

if (mysqli_stmt_execute($stmt)) {
    $new_id = mysqli_insert_id($conn);
    logActivity(
        $conn,
        $current_user_id,
        'create_staff',
        'Tambah kakitangan baru: ' . $name . ' (ID: ' . $new_id . ', Agensi: ' . $agency_type . ')'
    );
    header('Location: Senarai_Kakitangan.php?success=created');
    exit();
} else {
    header('Location: Senarai_Kakitangan.php?error=insert_failed');
    exit();
}
