<?php
/**
 * Tripper Record Delete Handler
 * Dozar & Tripper Management System
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';

// Check if user is logged in and has permission
$user = getCurrentUser();
if (!$user) {
    header('Location: ' . SITE_URL . '/login.php');
    exit;
}

// Only admin can delete records
if ($user['role'] !== 'admin') {
    $_SESSION['error_message'] = t('msg_error', 'You do not have permission to delete records');
    header('Location: ' . SITE_URL . '/reports/');
    exit;
}

// Get record ID
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$id) {
    $_SESSION['error_message'] = t('msg_error', 'Invalid record ID');
    header('Location: ' . SITE_URL . '/reports/');
    exit;
}

$pdo = getPDO();

try {
    // Check if record exists
    $stmt = $pdo->prepare("SELECT id, loading_photo_path, unloading_photo_path FROM tripper_records WHERE id = ?");
    $stmt->execute([$id]);
    $record = $stmt->fetch();
    
    if (!$record) {
        $_SESSION['error_message'] = t('msg_no_records', 'Record not found');
        header('Location: ' . SITE_URL . '/reports/');
        exit;
    }
    
    // Delete the record
    $stmt = $pdo->prepare("DELETE FROM tripper_records WHERE id = ?");
    $stmt->execute([$id]);
    
    // Optionally delete associated photos if exist
    if ($record['loading_photo_path'] && file_exists(__DIR__ . '/../uploads/' . $record['loading_photo_path'])) {
        unlink(__DIR__ . '/../uploads/' . $record['loading_photo_path']);
    }
    if ($record['unloading_photo_path'] && file_exists(__DIR__ . '/../uploads/' . $record['unloading_photo_path'])) {
        unlink(__DIR__ . '/../uploads/' . $record['unloading_photo_path']);
    }
    
    $_SESSION['success_message'] = t('msg_delete_success', 'Record deleted successfully!');
    
} catch (PDOException $e) {
    error_log("Delete error: " . $e->getMessage());
    $_SESSION['error_message'] = t('msg_error', 'Failed to delete record');
}

header('Location: ' . SITE_URL . '/reports/');
exit;
