<?php
// submit_application.php

ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'error_log.txt');

// Debugging logs (optional)
file_put_contents('debug_post.txt', print_r($_POST, true));
file_put_contents('debug_files.txt', print_r($_FILES, true));

require_once('../config/dbConnection.php');
require_once '../../thirdparty/phpqrcode/qrlib.php';

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

// Collect POST data
$businessName       = $_POST['businessName'];
$ownerName          = $_POST['ownerName'];
$owner_email        = $_POST['email'];
$businessType       = $_POST['businessType'];
$receiptNumber      = $_POST['receiptNumber'];
$location           = $_POST['location'];
$street             = $_POST['street'];
$phoneNumber        = $_POST['phoneNumber'];
$nrc                = $_POST['nrc'];
$businessCategory   = $_POST['businessCategory'];
$registrationType   = $_POST['registrationType'];
$healthpermitAmount = $_POST['healthpermitAmount'];
$firecertAmount     = $_POST['firecertAmount'];
$blevyAmount        = $_POST['blevyAmount'];
$status             = "Pending";

// Generate unique permit ID
$uniqueID = uniqid("permit_");

// Generate QR content
$qrContent = "Business Name: $businessName\nOwner Name: $ownerName\nEmail: $owner_email\nReceipt Number: $receiptNumber\nWard: $location\nConstituency: $street\nPhone: $phoneNumber\nStatus: $status\nPermit ID: $uniqueID\nNRC: $nrc";

// === QR Code Generation ===
$qrDir = __DIR__ . '/../../uploads/qrcodes/';
$qrFileName = $uniqueID . '.png';
$qrFilePathAbsolute = $qrDir . $qrFileName;
$qrFilePathRelative = 'uploads/qrcodes/' . $qrFileName;

// Ensure QR directory exists
if (!is_dir($qrDir)) {
    mkdir($qrDir, 0777, true);
}

// Generate QR code file
QRcode::png($qrContent, $qrFilePathAbsolute);

// === Attachment Upload ===
$fileAttachmentPath = null;

if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === 0) {
    $allowedTypes = ['pdf', 'png', 'jpeg', 'jpg'];
    $fileTmpName = $_FILES['attachment']['tmp_name'];
    $fileName = $_FILES['attachment']['name'];
    $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

    if (in_array($fileExtension, $allowedTypes)) {
        $uploadDir = __DIR__ . '/../../uploads/';
        $relativeDir = 'uploads/';
        $uniqueFileName = uniqid() . '.' . $fileExtension;
        $fileFullPath = $uploadDir . $uniqueFileName;
        $fileRelativePath = $relativeDir . $uniqueFileName;

        // Ensure upload directory exists
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        if (move_uploaded_file($fileTmpName, $fileFullPath)) {
            $fileAttachmentPath = $fileRelativePath;
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Error uploading the attachment file.']);
            exit;
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid file type. Only PDF, PNG, JPEG, JPG allowed.']);
        exit;
    }
}

// === Check for Duplicate Receipt Number ===
$receiptCheckStmt = $conn->prepare("SELECT COUNT(*) FROM permits WHERE receipt_number = ?");
$receiptCheckStmt->bind_param("s", $receiptNumber);
$receiptCheckStmt->execute();
$receiptCheckStmt->bind_result($receiptCount);
$receiptCheckStmt->fetch();
$receiptCheckStmt->close();

if ($receiptCount > 0) {
    echo json_encode(['status' => 'error', 'message' => 'Receipt number already exists. Please check and try again.']);
    exit;
}

// === Generate Unique Application Number ===
function generateUniqueApplicationNumber($conn) {
    do {
        $applicationNumber = random_int(100000000000, 999999999999);
        $stmt = $conn->prepare("SELECT COUNT(*) FROM permits WHERE application_number = ?");
        $stmt->bind_param("s", $applicationNumber);
        $stmt->execute();
        $stmt->bind_result($count);
        $stmt->fetch();
        $stmt->close();
    } while ($count > 0);

    return $applicationNumber;
}

$applicationNumber = generateUniqueApplicationNumber($conn);

// === Insert Permit into Database ===
$stmt = $conn->prepare("INSERT INTO permits (
    application_number, business_name, owner_name, owner_email, business_type, receipt_number, location, street, 
    phone_number, nrc, status, qr_code, attachment, business_category_id, blevy_amount, firecert_amount, 
    healthpermit_amount, entry_type
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

if (!$stmt) {
    echo json_encode(['status' => 'error', 'message' => 'Database error: prepare failed.']);
    exit;
}

$stmt->bind_param("ssssssssssssssddds",
    $applicationNumber,
    $businessName,
    $ownerName,
    $owner_email,
    $businessType,
    $receiptNumber,
    $location,
    $street,
    $phoneNumber,
    $nrc,
    $status,
    $qrFilePathRelative,
    $fileAttachmentPath,
    $businessCategory,
    $blevyAmount,
    $firecertAmount,
    $healthpermitAmount,
    $registrationType
);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Application submitted successfully.']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'DB Insert Error: ' . $stmt->error]);
}

$stmt->close();
$conn->close();
?>
