<?php
// permit_handler.php

session_start();
require_once('../config/dbConnection.php');
require_once('../../thirdparty/phpqrcode/qrlib.php');
require_once('sms_functions.php');  // adjust path for your sms_functions.php

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

// Create upload directories if not exist
$uploadDir = __DIR__ . '/../../uploads/';
$qrDir = $uploadDir . 'qrcodes/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
if (!is_dir($qrDir)) mkdir($qrDir, 0777, true);

function sanitize($value) {
    return trim(htmlspecialchars($value));
}

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;
}

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

    if ($file['error'] === 0) {
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExts)) return false;

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

        if (move_uploaded_file($file['tmp_name'], $fullPath)) {
            // Delete old file if exists
            if ($oldPath && file_exists(__DIR__ . '/../../' . $oldPath)) {
                @unlink(__DIR__ . '/../../' . $oldPath);
            }
            return $relativePath;
        }
    }
    return false;
}

function generateQRCode($data, $existingQrPath = null) {
    global $qrDir;

    if ($existingQrPath) {
        $qrRelativePath = $existingQrPath;
        $qrFullPath = __DIR__ . '/../../' . $qrRelativePath;
    } else {
        $qrRelativePath = 'uploads/qrcodes/permit_' . time() . '_' . mt_rand(1000, 9999) . '.png';
        $qrFullPath = __DIR__ . '/../../' . $qrRelativePath;
    }

    if (file_exists($qrFullPath)) {
        @unlink($qrFullPath);
    }

    QRcode::png($data, $qrFullPath);
    return file_exists($qrFullPath) ? $qrRelativePath : false;
}

function insertOrUpdateClient($conn, $clientName, $nrc, $mobilePhone, $email) {
    $sql = "INSERT INTO clients (ClientName, NRC, MobilePhone, email) 
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE MobilePhone = VALUES(MobilePhone), email = VALUES(email)";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        error_log("CLIENT INSERT PREPARE ERROR: " . $conn->error);
        return false;
    }

    $stmt->bind_param("ssss", $clientName, $nrc, $mobilePhone, $email);
    $result = $stmt->execute();

    if (!$result) {
        error_log("CLIENT INSERT EXECUTE ERROR: " . $stmt->error);
    }

    $stmt->close();
    return $result;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
    exit;
}

// Check user session (adjust according to your auth system)
if (!isset($_SESSION['username'], $_SESSION['role'])) {
    echo json_encode(['status' => 'error', 'message' => 'Session expired. Please login again.']);
    exit;
}

// Sanitize inputs
$businessName       = sanitize($_POST['businessName'] ?? '');
$ownerName          = sanitize($_POST['ownerName'] ?? '');
$owner_email        = sanitize($_POST['email'] ?? '');
$businessType       = sanitize($_POST['businessType'] ?? '');
$receiptNumber      = sanitize($_POST['receiptNumber'] ?? '');
$location           = sanitize($_POST['location'] ?? '');
$street             = sanitize($_POST['street'] ?? '');
$phoneNumber        = sanitize($_POST['phoneNumber'] ?? '');
$nrc                = sanitize($_POST['nrc'] ?? '');
$businessCategory   = intval($_POST['businessCategory'] ?? 0);
$registrationType   = sanitize($_POST['registrationType'] ?? '');
$healthpermitAmount = floatval($_POST['healthpermitAmount'] ?? 0);
$firecertAmount     = floatval($_POST['firecertAmount'] ?? 0);
$blevyAmount        = floatval($_POST['blevyAmount'] ?? 0);
$comment            = sanitize($_POST['comment'] ?? '');
$status             = sanitize($_POST['status'] ?? 'Pending');
$permitType         = "BusinessLevy";

$username    = $_SESSION['username'];
$employeeNo  = $_SESSION['employee_no'] ?? '';
$userRole    = $_SESSION['role'];
$fullIdentity = $username . "EMP" . $employeeNo;

// Validate required fields
$requiredFields = [
    'Business Name' => $businessName,
    'Owner Name' => $ownerName,
    //'Owner Email' => $owner_email,
    'Business Type' => $businessType,
    'Receipt Number' => $receiptNumber,
    'Location' => $location,
    'Street' => $street,
    'Phone Number' => $phoneNumber,
    'NRC' => $nrc,
    'Business Category' => $businessCategory,
    'Registration Type' => $registrationType,
];

foreach ($requiredFields as $fieldName => $value) {
    if (empty($value)) {
        echo json_encode(['status' => 'error', 'message' => "Required field missing: $fieldName"]);
        exit;
    }
}

$isUpdate = isset($_GET['id']) && is_numeric($_GET['id']);
if ($isUpdate) {
    // UPDATE existing permit
    $permitId = intval($_GET['id']);

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

    if (!$existing) {
        echo json_encode(['status' => 'error', 'message' => 'Permit not found.']);
        exit;
    }

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

    // Handle file upload if new file submitted
    if (!empty($_FILES['attachment']['name'])) {
        $newAttachment = handleFileUpload($_FILES['attachment'], $attachment);
        if (!$newAttachment) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid or failed file upload.']);
            exit;
        }
        $attachment = $newAttachment;
    }

    // Generate QR content
    $qrContent = "Business Name: $businessName\nPhone: $phoneNumber\nNRC: $nrc\nEmail: $owner_email\nReceipt Number: $receiptNumber\nRegistration Type: $registrationType\nBusiness Type: $businessType\nLocation: $location\nStreet: $street\nStatus: $status\nPermit ID: $applicationNumber";

    $qrRelativePath = generateQRCode($qrContent, $existingQrPath);

    // Prepare update query based on role
    if ($userRole === 'Auditor') {
        $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=?, status=?, comment=?, 
            audited_by=? WHERE id=?");
        $stmt->bind_param("ssssssssssddssssssi",
            $businessName, $phoneNumber, $nrc, $owner_email, $receiptNumber,
            $registrationType, $businessType, $location, $street, $businessCategory,
            $blevyAmount, $firecertAmount, $healthpermitAmount,
            $attachment, $qrRelativePath, $status, $comment, $fullIdentity, $permitId);

    } elseif ($userRole === 'Legal') {
        $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=?, status=?, comment=?, 
            verified_by=? WHERE id=?");
        $stmt->bind_param("ssssssssssddssssssi",
            $businessName, $phoneNumber, $nrc, $owner_email, $receiptNumber,
            $registrationType, $businessType, $location, $street, $businessCategory,
            $blevyAmount, $firecertAmount, $healthpermitAmount,
            $attachment, $qrRelativePath, $status, $comment, $fullIdentity, $permitId);

    } else {
        $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=?, status=?, comment=? 
            WHERE id=?");
        $stmt->bind_param("ssssssssssddsssssi",
            $businessName, $phoneNumber, $nrc, $owner_email, $receiptNumber,
            $registrationType, $businessType, $location, $street, $businessCategory,
            $blevyAmount, $firecertAmount, $healthpermitAmount,
            $attachment, $qrRelativePath, $status, $comment, $permitId);
    }

    if ($stmt->execute()) {
        $oldStatusTrimmed = strtolower(trim($oldStatus));
        $newStatusTrimmed = strtolower(trim($status));

        error_log("Old status: [$oldStatus], New status: [$status]");
        error_log("Trimmed old status: [$oldStatusTrimmed], Trimmed new status: [$newStatusTrimmed]");

        if ($oldStatusTrimmed !== $newStatusTrimmed && in_array($newStatusTrimmed, ['verified', 'approved'])) {
            $statusText = $newStatusTrimmed === 'verified' ? 'Reviewed' : 'Approved';
            $ownerNameUc = ucwords(strtolower($ownerName));
            $msg = "Dear $ownerNameUc, we wish to inform you that your permit application (No. $applicationNumber) has been $statusText and is currently awaiting Approval. Thank you.";

            error_log("Sending SMS to $phoneNumber with message: $msg");
            $sendResult = sendZamtelSms($phoneNumber, $msg);
            error_log("SMS send result: " . var_export($sendResult, true));
        }

        echo json_encode(['status' => 'success', 'message' => 'Permit updated successfully.', 'qr' => $qrRelativePath]);
    } else {
        error_log("UPDATE ERROR: " . $stmt->error);
        echo json_encode(['status' => 'error', 'message' => 'Update failed: ' . $stmt->error]);
    }

    $stmt->close();

} else {
    // INSERT new permit
    $applicationNumber = generateUniqueApplicationNumber($conn);

    // Insert or update client first
    if (!insertOrUpdateClient($conn, $ownerName, $nrc, $phoneNumber, $owner_email)) {
        echo json_encode(['status' => 'error', 'message' => 'Failed to insert/update client record.']);
        exit;
    }

    $qrContent = "Business Name: $businessName\nOwner Name: $ownerName\nEmail: $owner_email\nReceipt Number: $receiptNumber\nWard: $location\nConstituency: $street\nPhone: $phoneNumber\nStatus: $status\nPermit ID: $applicationNumber\nNRC: $nrc";
    $qrRelativePath = generateQRCode($qrContent);

    $attachmentPath = null;
    if (!empty($_FILES['attachment']['name'])) {
        $attachmentPath = handleFileUpload($_FILES['attachment']);
        if (!$attachmentPath) {
            echo json_encode(['status' => 'error', 'message' => 'Attachment upload failed.']);
            exit;
        }
    }

    $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, permit_type, comment
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

    $stmt->bind_param("ssssssssssssssddssss",
        $applicationNumber, $businessName, $ownerName, $owner_email, $businessType,
        $receiptNumber, $location, $street, $phoneNumber, $nrc, $status,
        $qrRelativePath, $attachmentPath, $businessCategory, $blevyAmount, $firecertAmount,
        $healthpermitAmount, $registrationType, $permitType, $comment);

    if ($stmt->execute()) {
        // SMS INTEGRATION: Notify applicant on submission
        $ownerNameUc = ucwords(strtolower($ownerName));
        $msg = "Dear $ownerNameUc, your permit application ($applicationNumber) has been received and is currently $status review.";
        sendZamtelSms($phoneNumber, $msg);

        echo json_encode(['status' => 'success', 'message' => 'Application submitted successfully.', 'qr' => $qrRelativePath]);
    } else {
        error_log("INSERT ERROR: " . $stmt->error);
        echo json_encode(['status' => 'error', 'message' => 'Database insert error: ' . $stmt->error]);
    }
    $stmt->close();
}

$conn->close();
