<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

require_once 'db/config.php';

if (isset($_GET['id'])) {
    $pdo = db();
    $id = $_GET['id'];

    // First, fetch the paths of the vouchers to delete the files
    $stmt = $pdo->prepare('SELECT voucher_adelanto_path, voucher_restante_path FROM pedidos WHERE id = ?');
    $stmt->execute([$id]);
    $paths = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($paths) {
        if (!empty($paths['voucher_adelanto_path']) && file_exists($paths['voucher_adelanto_path'])) {
            unlink($paths['voucher_adelanto_path']);
        }
        if (!empty($paths['voucher_restante_path']) && file_exists($paths['voucher_restante_path'])) {
            unlink($paths['voucher_restante_path']);
        }
    }

    // Now, delete the record from the database
    $stmt = $pdo->prepare('DELETE FROM pedidos WHERE id = ?');
    $stmt->execute([$id]);

    $redirect_url = 'pedidos.php';
    if (isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])) {
        $redirect_url = $_SERVER['HTTP_REFERER'];
    }
    // Add a query parameter to the redirect URL
    if (strpos($redirect_url, '?') === false) {
        $redirect_url .= '?deleted=true';
    } else {
        $redirect_url .= '&deleted=true';
    }
    header('Location: ' . $redirect_url);
    exit;
} else {
    header('Location: pedidos.php');
    exit;
}