<?php

// app/includes/update_permit.php
require_once(__DIR__ . '/../config/dbConnection.php');
require_once(__DIR__ . '/../../thirdparty/phpqrcode/qrlib.php');

$db = DatabaseConnection::getInstance();
$conn = $db->getConnection();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['id'])) {
    $permitId = intval($_GET['id']); // Always cast IDs to int

    // === Sanitize Inputs ===
    $businessName       = trim($_POST['businessName']);
    $phoneNumber        = trim($_POST['phoneNumber']);
    $nrc                = trim($_POST['nrc']);
    $email              = trim($_POST['email']);
    $receiptNumber      = trim($_POST['receiptNumber']);
    $registrationType   = trim($_POST['registrationType']);
    $businessType       = trim($_POST['businessType']);
    $location           = trim($_POST['location']);
    $street             = trim($_POST['street']);
    $categoryId         = intval($_POST['businessCategory']);
    $blevyAmount        = floatval($_POST['blevyAmount']);
    $firecertAmount     = floatval($_POST['firecertAmount']);
    $healthpermitAmount = floatval($_POST['healthpermitAmount']);

    // === Fetch existing permit details ===
    $stmt = $conn->prepare("SELECT attachment, application_number, qr_code FROM permits WHERE id = ?");
    $stmt->bind_param("i", $permitId);
    $stmt->execute();
    $result = $stmt->get_result();
    $existing = $result->fetch_assoc();
    $stmt->close();

    if (!$existing) {
        echo "❌ Permit not found.";
        exit;
    }

    $attachment = $existing['attachment'];
    $applicationNumber = $existing['application_number'];
    $existingQrPath = $existing['qr_code'];

    // === Handle Attachment Upload ===
    if (!empty($_FILES['attachment']['name'])) {
        $uploadDir = __DIR__ . '/../../uploads/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $fileExt = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        $allowedExts = ['pdf', 'png', 'jpg', 'jpeg'];
        if (!in_array($fileExt, $allowedExts)) {
            echo "❌ Invalid file type.";
            exit;
        }

        $uniqueName = uniqid() . '.' . $fileExt;
        $uploadPath = $uploadDir . $uniqueName;
        $relativePath = 'uploads/' . $uniqueName;

        if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadPath)) {
            // ✅ Delete old attachment if it exists and is different
            $oldAttachmentPath = __DIR__ . '/../../' . $attachment;
            if (!empty($attachment) && file_exists($oldAttachmentPath)) {
                unlink($oldAttachmentPath);
            }

            $attachment = $relativePath;
        } else {
            echo "❌ Failed to upload attachment.";
            exit;
        }
    }

    // === Regenerate QR Code ===
    $qrDir = __DIR__ . '/../../uploads/qrcodes/';
    if (!is_dir($qrDir)) {
        mkdir($qrDir, 0777, true);
    }

    if (!is_writable($qrDir)) {
        echo "❌ QR code folder is not writable.";
        exit;
    }

    // Determine QR file path
    if (!empty($existingQrPath)) {
        $qrRelativePath = $existingQrPath;
        $qrFullPath = __DIR__ . '/../../' . $existingQrPath;
    } else {
        $qrRelativePath = 'uploads/qrcodes/' . uniqid('permit_') . '.png';
        $qrFullPath = __DIR__ . '/../../' . $qrRelativePath;
    }

    $qrContent = "Business Name: $businessName\nPhone: $phoneNumber\nNRC: $nrc\nEmail: $email\nReceipt Number: $receiptNumber\nRegistration Type: $registrationType\nBusiness Type: $businessType\nLocation: $location\nStreet: $street\nStatus: Active\nPermit ID: $applicationNumber";

    // Generate QR
    QRcode::png($qrContent, $qrFullPath);

    if (!file_exists($qrFullPath)) {
        echo "❌ Failed to save QR code at $qrFullPath";
        exit;
    }

    // === Update Permit Record ===
    $stmt = $conn->prepare("UPDATE permits SET 
        business_name = ?, phone_number = ?, nrc = ?, owner_email = ?, receipt_number = ?, entry_type = ?, 
        business_type = ?, location = ?, street = ?, business_category_id = ?, blevy_amount = ?, firecert_amount = ?, 
        healthpermit_amount = ?, attachment = ?, qr_code = ? 
        WHERE id = ?");

    $stmt->bind_param(
        "ssssssssssddsssi",
        $businessName,
        $phoneNumber,
        $nrc,
        $email,
        $receiptNumber,
        $registrationType,
        $businessType,
        $location,
        $street,
        $categoryId,
        $blevyAmount,
        $firecertAmount,
        $healthpermitAmount,
        $attachment,
        $qrRelativePath,
        $permitId
    );

    if ($stmt->execute()) {
        $browserQrPath = '/' . $qrRelativePath;

        echo "<h3>✅ Permit updated and QR code regenerated successfully!</h3>";
        echo "<p><strong>Business:</strong> " . htmlspecialchars($businessName) . "</p>";
        echo "<p><strong>QR Code:</strong></p>";

        echo "<img src='" . htmlspecialchars($browserQrPath) . "' alt='QR Code' style='width: 200px; height: 200px; border: 1px solid #ccc;'><br><br>";
        echo "<a href='" . htmlspecialchars($browserQrPath) . "' download>⬇️ Download QR Code</a>";
        echo "<br><a href='permits_list.php'>🔙 Back to List</a>";
    } else {
        echo "❌ Error updating permit: " . $stmt->error;
    }

    $stmt->close();
}
?>
