<?php
/**
 * Delete ALL employee transfers in a date range for current site
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();

$siteId = getCurrentSiteId();
$fromDate = sanitize($_GET['from_date'] ?? '');
$toDate = sanitize($_GET['to_date'] ?? '');

if (!$fromDate || !$toDate) {
    redirect(BASE_URL . '/modules/transfer/report.php', 'Invalid date range for delete all.', 'error');
}

try {
    $db = getDB();
    $db->beginTransaction();

    // Delete transfers where from_site or to_site is this site
    $stmt = $db->prepare("
        DELETE FROM employee_transfers
        WHERE transfer_date BETWEEN :from_date AND :to_date
          AND (from_site_id = :site_id OR to_site_id = :site_id)
    ");

    $stmt->execute([
        ':from_date' => $fromDate,
        ':to_date' => $toDate,
        ':site_id' => $siteId,
    ]);

    $deletedCount = $stmt->rowCount();

    $db->commit();

    if (function_exists('logAudit')) {
        // Keep audit logging simple to avoid argument mismatch issues
        // Just record that a bulk delete happened for employee_transfers
        try {
            logAudit('DELETE', 'employee_transfers', null);
        } catch (Exception $e) {
            // Do not fail the operation if audit logging has issues
            error_log('Transfer delete all audit log error: ' . $e->getMessage());
        }
    }

    $params = http_build_query([
        'from_date' => $fromDate,
        'to_date' => $toDate,
    ]);

    redirect(BASE_URL . '/modules/transfer/report.php?' . $params, "Deleted {$deletedCount} transfer(s) successfully.");

} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollBack();
    }
    error_log('Delete all transfers error: ' . $e->getMessage());
    redirect(BASE_URL . '/modules/transfer/report.php', 'Error deleting transfers.', 'error');
}


