<?php
/**
 * Delete a single employee transfer record
 */

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

$transferId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$employeeId = isset($_GET['emp_id']) ? (int)$_GET['emp_id'] : 0;
$transferDate = sanitize($_GET['tdate'] ?? '');
$fromDate = sanitize($_GET['from_date'] ?? '');
$toDate = sanitize($_GET['to_date'] ?? '');

// Validate basic identifiers
if ($transferId < 0 || ($transferId === 0 && ($employeeId <= 0 || empty($transferDate)))) {
    redirect(BASE_URL . '/modules/transfer/report.php', 'Invalid transfer ID.', 'error');
}

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

    if ($transferId > 0) {
        // Normal case: use primary key
        $stmt = $db->prepare("DELETE FROM employee_transfers WHERE transfer_id = ? LIMIT 1");
        $stmt->execute([$transferId]);
    } else {
        // Fallback for old data where transfer_id is 0:
        // use employee_id + transfer_date to target a single row
        $stmt = $db->prepare("
            DELETE FROM employee_transfers 
            WHERE employee_id = ? AND transfer_date = ? 
            ORDER BY transfer_id ASC 
            LIMIT 1
        ");
        $stmt->execute([$employeeId, $transferDate]);
    }

    $db->commit();

    if (function_exists('logAudit')) {
        logAudit('DELETE', 'employee_transfers', $transferId);
    }

    // Preserve filters in redirect if available
    $redirectUrl = BASE_URL . '/modules/transfer/report.php';
    $params = [];
    if ($fromDate) $params['from_date'] = $fromDate;
    if ($toDate) $params['to_date'] = $toDate;

    if (!empty($params)) {
        $redirectUrl .= '?' . http_build_query($params);
    }

    redirect($redirectUrl, 'Transfer deleted successfully.');

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


