<?php
// saveHealthPermit.php

function handleFileUpload($file, $oldPath = null) {
    $allowedExts = ['pdf', 'png', 'jpeg', 'jpg'];
    $uploadDir = __DIR__ . '/../../uploads/';
    $relativeDir = 'uploads/';

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0775, true);
    }

    if ($file && isset($file['error']) && $file['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExts)) {
            throw new Exception("Invalid file type: $ext");
        }

        $uniqueName = uniqid('attch_', true) . '.' . $ext;
        $fullPath = $uploadDir . $uniqueName;
        $relativePath = $relativeDir . $uniqueName;

        if (!move_uploaded_file($file['tmp_name'], $fullPath)) {
            throw new Exception("Failed to move uploaded file.");
        }

        if ($oldPath && file_exists(__DIR__ . '/../../' . $oldPath)) {
            @unlink(__DIR__ . '/../../' . $oldPath);
        }

        return $relativePath;
    }
    return null;
}

// Insert function
function insertHealthPermit($data, $conn) {
    $data['permit_number'] = str_pad(random_int(0, 999999999999), 12, '0', STR_PAD_LEFT);
    $data['permit_category'] = 'HealthPermit';

    $sql = "INSERT INTO healthpermits (
        application_number, permit_number, business_name, owner_name, business_type,
        permit_category, receipt_number, location, street, phone_number, status,
        entry_type, permit_type, submitted_at, owner_email, qr_code, attachment,
        nrc, comment, approved_by, approved_date, business_category_id,
        healthpermit_amount, audited_by, verified_by, employee_no, notified
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?, ?, ?, NULL, NULL, ?, ?, NULL, NULL, ?, ?)";

    if (!$stmt = $conn->prepare($sql)) {
        die("Prepare failed: (" . $conn->errno . ") " . $conn->error);
    }

    // Bind params: 24 placeholders => 24 parameters
    $stmt->bind_param(
        "ssssssssssssssssssiddi", 
        $data['application_number'], $data['permit_number'], $data['business_name'],
        $data['owner_name'], $data['business_type'], $data['permit_category'],
        $data['receipt_number'], $data['location'], $data['street'], $data['phone_number'],
        $data['status'], $data['entry_type'], $data['permit_type'],
        $data['owner_email'], $data['qr_code'], $data['attachment'],
        $data['nrc'], $data['comment'], $data['business_category_id'],
        $data['healthpermit_amount'], $data['employee_no'], $data['notified']
    );

    if (!$stmt->execute()) {
        die("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
    }

    return $stmt->insert_id;
}

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

$fields = [
    'application_number', 'permit_number', 'business_name', 'owner_name', 'business_type',
    'permit_category', 'receipt_number', 'location', 'street', 'phone_number', 'status',
    'entry_type', 'permit_type', 'submitted_at', 'owner_email', 'qr_code', 'attachment',
    'nrc', 'comment', 'business_category_id', 'healthpermit_amount', 'employee_no', 'notified'
];

// Initialize values
$values = array_fill_keys($fields, '');

// Prefill from permits if application_number present
if (!empty($_GET['application_number'])) {
    $stmt = $conn->prepare("SELECT * FROM permits WHERE application_number = ? LIMIT 1");
    $stmt->bind_param('s', $_GET['application_number']);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $row = $result->fetch_assoc()) {
        foreach ($fields as $field) {
            if (in_array($field, ['permit_number', 'permit_category'])) continue;
            $values[$field] = htmlspecialchars($row[$field] ?? '');
        }
    }
}


$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Populate $values with POST data except 'permit_number', 'permit_category', 'attachment'
    foreach ($fields as $field) {
        if (in_array($field, ['permit_number', 'permit_category', 'attachment'])) {
            continue;
        }
        $values[$field] = isset($_POST[$field]) ? trim($_POST[$field]) : '';
    }

    $values['status'] = 'Pending';
    $values['notified'] = isset($_POST['notified']) ? (int)$_POST['notified'] : 0;

    try {
        // Handle file upload if file was sent
        $uploadPath = handleFileUpload($_FILES['attachment'] ?? null);
        $values['attachment'] = $uploadPath ?? null;

        $newId = insertHealthPermit($values, $conn);

        header("Location: addHealthPermit.php?success=1&id=$newId");
        exit;
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}
