<?php
// delete_gate_enquiry.php
session_start();

// Load DB connection (adjust path/name if needed)
require_once 'config.php'; // expects $pdo (PDO) or require_once 'db.php' for mysqli $conn

header('Content-Type: application/json');

// Permission checks
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access. Please login.']);
    exit;
}

// Only allow super admins to delete
// If your session stores is_super_admin as 1/0 or true/false adapt accordingly
if (empty($_SESSION['is_super_admin']) || $_SESSION['is_super_admin'] != 1) {
    echo json_encode(['success' => false, 'message' => 'Access denied. Only super admins can delete enquiries.']);
    exit;
}

// Must be POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit;
}

// Accept either enquiry_id or id (backwards compatibility)
$enquiryId = intval($_POST['enquiry_id'] ?? $_POST['id'] ?? 0);
if ($enquiryId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid enquiry id.']);
    exit;
}

try {
    // If PDO is available (config.php provided $pdo)
    if (isset($pdo) && $pdo instanceof PDO) {
        // fetch file paths
        $stmt = $pdo->prepare("SELECT photo_path, document_path FROM gate_enquiries WHERE enquiry_id = :eid");
        $stmt->execute([':eid' => $enquiryId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$row) {
            echo json_encode(['success' => false, 'message' => 'Enquiry not found.']);
            exit;
        }

        // delete DB record
        $del = $pdo->prepare("DELETE FROM gate_enquiries WHERE enquiry_id = :eid");
        $del->execute([':eid' => $enquiryId]);

    } elseif (isset($conn) && $conn instanceof mysqli) {
        // mysqli fallback
        $stmt = $conn->prepare("SELECT photo_path, document_path FROM gate_enquiries WHERE enquiry_id = ?");
        $stmt->bind_param('i', $enquiryId);
        $stmt->execute();
        $res = $stmt->get_result();
        $row = $res->fetch_assoc();
        $stmt->close();

        if (!$row) {
            echo json_encode(['success' => false, 'message' => 'Enquiry not found.']);
            exit;
        }

        $stmt = $conn->prepare("DELETE FROM gate_enquiries WHERE enquiry_id = ?");
        $stmt->bind_param('i', $enquiryId);
        $stmt->execute();
        $stmt->close();

    } else {
        // No DB object found
        error_log("delete_gate_enquiry.php - No DB connection available.");
        echo json_encode(['success' => false, 'message' => 'Server misconfiguration: DB connection not found.']);
        exit;
    }

    // Delete files if they exist (photo_path, document_path)
    foreach (['photo_path', 'document_path'] as $field) {
        if (!empty($row[$field])) {
            $file = $row[$field];

            // try absolute path first, then relative to script
            if (file_exists($file)) {
                @unlink($file);
            } else {
                $alt = __DIR__ . '/' . ltrim($file, '/\\');
                if (file_exists($alt)) {
                    @unlink($alt);
                }
            }
        }
    }

    echo json_encode(['success' => true, 'message' => 'Enquiry deleted successfully.']);
    exit;

} catch (Exception $e) {
    // Log server-side error and return generic message
    error_log("delete_gate_enquiry.php error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Server error: could not delete enquiry.']);
    exit;
}
