<?php
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_kpra_config'])) {
    $is_enabled = isset($_POST['is_enabled']) ? 1 : 0;
    $key = $_POST['key'] ?? '';
    $business_id = $_POST['business_id'] ?? '';
    $api_url = $_POST['api_url'] ?? 'http://kpra.gov.pk/rims/integration/';

    // Check if a row exists
    $check = mysqli_fetch_assoc(mysqli_query($conn, "SELECT id FROM kpra_config LIMIT 1"));

    if ($check) {
        // Update existing row
        mysqli_query($conn, "UPDATE kpra_config SET 
            is_enabled = $is_enabled,
            `key` = '" . mysqli_real_escape_string($conn, $key) . "',
            business_id = '" . mysqli_real_escape_string($conn, $business_id) . "',
            api_url = '" . mysqli_real_escape_string($conn, $api_url) . "',
            updated_at = NOW()
            LIMIT 1
        ");
    } else {
        // Insert new row
        mysqli_query($conn, "INSERT INTO kpra_config (is_enabled, `key`, business_id, api_url)
            VALUES (
                $is_enabled,
                '" . mysqli_real_escape_string($conn, $key) . "',
                '" . mysqli_real_escape_string($conn, $business_id) . "',
                '" . mysqli_real_escape_string($conn, $api_url) . "'
            )");
    }

    echo "<div class='alert alert-success'>KPRA settings saved successfully.</div>";
}

// Load current settings or use default fallback
$kpra = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM kpra_config LIMIT 1")) ?? [
    'is_enabled' => 0,
    'key' => '',
    'business_id' => '',
    'api_url' => 'http://kpra.gov.pk/rims/integration/'
];

// Get NTN from branch_info
$branch_ntn = '';
$branch_result = mysqli_query($conn, "SELECT ntn FROM branch_info LIMIT 1");
if ($branch_result && $branch_row = mysqli_fetch_assoc($branch_result)) {
    $branch_ntn = $branch_row['ntn'] ?? '';
}
?>

<div class="connected-app-card d-flex w-100">
    <ul class="w-100">
        <li class="flex-column align-items-start w-100">
            <form method="post" class="row g-3 w-100">
                <input type="hidden" name="update_kpra_config" value="1">

                <div class="col-md-12 form-check form-switch mb-2">
                    <input type="checkbox" class="form-check-input" id="is_enabled" name="is_enabled" <?= $kpra['is_enabled'] ? 'checked' : '' ?>>
                    <label class="form-check-label" for="is_enabled">Enable KPRA Integration</label>
                </div>

                <!-- NTN Display Section -->
                <div class="col-12">
                    <div class="alert alert-info">
                        <h6><i data-feather="info" class="feather-14 me-1"></i> Current NTN Configuration</h6>
                        <p class="mb-1"><strong>Branch NTN:</strong> 
                            <?php if (!empty($branch_ntn)): ?>
                                <span class="badge bg-success"><?= htmlspecialchars($branch_ntn) ?></span>
                            <?php else: ?>
                                <span class="badge bg-warning">Not Configured</span>
                                <small class="d-block text-muted">Please set NTN in branch settings first</small>
                            <?php endif; ?>
                        </p>
                        <small class="text-muted">This NTN will be used for all KPRA invoice submissions</small>
                    </div>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Private Key</label>
                    <input type="password" class="form-control" name="key" value="<?= htmlspecialchars($kpra['key']) ?>" placeholder="Enter your private key">
                    <small class="form-text text-muted">Private key provided by KPRA</small>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Business ID</label>
                    <input type="text" class="form-control" name="business_id" value="<?= htmlspecialchars($kpra['business_id']) ?>" placeholder="Enter your business ID">
                    <small class="form-text text-muted">Optional: For more accurate QR code verification</small>
                </div>

                <div class="col-md-6">
                    <label class="form-label">API URL</label>
                    <input type="text" class="form-control" name="api_url" value="<?= htmlspecialchars($kpra['api_url']) ?>">
                    <small class="form-text text-muted">KPRA API endpoint (default: http://kpra.gov.pk/rims/integration/)</small>
                </div>

                <div class="col-12">
                    <div class="alert alert-info">
                        <h6><i data-feather="info" class="feather-14 me-1"></i> KPRA Integration Information</h6>
                        <ul class="mb-0">
                            <li>Automatically sends invoice data to KPRA when a sale is completed</li>
                            <li>Generates QR codes for invoice verification</li>
                            <li>Requires internet connectivity to function</li>
                            <li>Uses NTN from branch settings (configure in branch settings)</li>
                            <li>Contact KPRA to obtain your private key</li>
                        </ul>
                    </div>
                </div>

                <div class="col-12">
                    <button class="btn btn-primary" type="submit">Save KPRA Settings</button>
                </div>
            </form>
        </li>
    </ul>
</div>
