<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

$staffModuleBoot = 'staff_module_boot';
$validateStaffPayload = 'validate_staff_payload';
$findStaffOrAbort = 'find_staff_or_abort';

$staffModuleBoot();

if (!is_post()) {
    redirect('app/modules/staff/index.php');
}

require_valid_csrf();

$action = (string) ($_POST['action'] ?? '');

if ($action === 'create') {
    remember_old_input($_POST);
    $errors = [];
    $payload = $validateStaffPayload($_POST, $errors);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the staff form errors.']);
        redirect('app/modules/staff/create.php' . (!is_club_admin() && $payload['club_id'] > 0 ? '?club_id=' . $payload['club_id'] : ''));
    }

    $photoPath = null;
    if (isset($_FILES['photo']) && ($_FILES['photo']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
        try {
            $photoPath = upload_file($_FILES['photo'], ['directory' => 'staff', 'max_size' => 2 * 1024 * 1024]);
        } catch (RuntimeException $exception) {
            flash('errors', ['photo' => $exception->getMessage()]);
            flash('error', ['type' => 'danger', 'message' => $exception->getMessage()]);
            redirect('app/modules/staff/create.php' . (!is_club_admin() && $payload['club_id'] > 0 ? '?club_id=' . $payload['club_id'] : ''));
        }
    }

    db_query(
        'INSERT INTO club_staff (club_id, full_name, role, phone, email, photo, status, created_at)
         VALUES (:club_id, :full_name, :role, :phone, :email, :photo, :status, NOW())',
        $payload + ['photo' => $photoPath]
    );

    $staffId = (int) db()->lastInsertId();
    audit_log('create_club_staff', 'staff', $staffId, null, $payload + ['photo' => $photoPath]);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Club staff record created successfully.']);
    redirect('app/modules/staff/view.php?id=' . $staffId);
}

if ($action === 'update') {
    $staffId = (int) ($_POST['id'] ?? 0);
    $existingStaff = $findStaffOrAbort($staffId);
    remember_old_input($_POST);
    $errors = [];
    $payload = $validateStaffPayload($_POST, $errors, $existingStaff);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the staff form errors.']);
        redirect('app/modules/staff/edit.php?id=' . $staffId);
    }

    $photoPath = $existingStaff['photo'];
    if (isset($_FILES['photo']) && ($_FILES['photo']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
        try {
            $photoPath = upload_file($_FILES['photo'], ['directory' => 'staff', 'max_size' => 2 * 1024 * 1024]);
            delete_uploaded_file($existingStaff['photo']);
        } catch (RuntimeException $exception) {
            flash('errors', ['photo' => $exception->getMessage()]);
            flash('error', ['type' => 'danger', 'message' => $exception->getMessage()]);
            redirect('app/modules/staff/edit.php?id=' . $staffId);
        }
    }

    db_query(
        'UPDATE club_staff
         SET club_id = :club_id,
             full_name = :full_name,
             role = :role,
             phone = :phone,
             email = :email,
             photo = :photo,
             status = :status
         WHERE id = :id',
        $payload + ['photo' => $photoPath, 'id' => $staffId]
    );

    audit_log('update_club_staff', 'staff', $staffId, $existingStaff, $payload + ['photo' => $photoPath]);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Club staff record updated successfully.']);
    redirect('app/modules/staff/view.php?id=' . $staffId);
}

if ($action === 'delete') {
    $staffId = (int) ($_POST['id'] ?? 0);
    $existingStaff = $findStaffOrAbort($staffId);

    db_query('DELETE FROM club_staff WHERE id = :id', ['id' => $staffId]);
    delete_uploaded_file($existingStaff['photo']);
    audit_log('delete_club_staff', 'staff', $staffId, $existingStaff, null);
    flash('success', ['type' => 'success', 'message' => 'Club staff record deleted successfully.']);
    redirect('app/modules/staff/index.php' . (!is_club_admin() ? '?club_id=' . (int) $existingStaff['club_id'] : ''));
}

redirect('app/modules/staff/index.php');
