<?php
/**
 * Public Branch Registration Form (Franchise Application)
 *
 * Fields: Center Name, Owner Name, Email, Phone, State, District, Pincode,
 *         Address, Plan (Free/Silver/Gold), Captcha, Payment Mode (for paid plans).
 *
 * @var array $plans
 * @var string $csrfToken
 * @var string $flash_error
 * @var string $flash_success
 * @var string $basePath
 */
$bp = $basePath ?? (defined('BASE_PATH') ? BASE_PATH : '/gmind');
$plans = $plans ?? [];

// Load Indian states + districts
$indianStates = [];
$statesFile = (defined('APP_ROOT') ? APP_ROOT : dirname(__DIR__, 3)) . '/config/indian_states.php';
if (file_exists($statesFile)) {
    $indianStates = require $statesFile;
}

// Payment settings (passed from controller or use defaults)
$upiId = $upiId ?? 'gmind@upi';
$upiName = $upiName ?? 'Gmind Institute';
$paymentPhone = $paymentPhone ?? '9305640290';

// Generate captcha (simple math)
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (empty($_SESSION['franchise_captcha'])) {
    $a = rand(1, 9);
    $b = rand(1, 9);
    $_SESSION['franchise_captcha'] = $a + $b;
    $_SESSION['franchise_captcha_text'] = "{$a} + {$b} = ?";
}
?>
<style>
.fr-reg { background: #f4f7fc; padding: 50px 0; }
.fr-wrap { max-width: 820px; margin: 0 auto; padding: 0 20px; }
.fr-header { text-align: center; margin-bottom: 28px; }
.fr-header h1 { font-family: 'Poppins', sans-serif; font-size: 2rem; color: #0d2b6e; margin: 0 0 6px; }
.fr-header p { font-size: 1rem; color: #666; margin: 0; }
.fr-card { background: #fff; border-radius: 16px; padding: 36px; box-shadow: 0 8px 32px rgba(13,43,110,0.08); }
.fr-section { margin-bottom: 28px; }
.fr-section h3 { font-family:'Poppins',sans-serif; font-size:1.05rem; color:#0d2b6e; margin:0 0 14px; padding-bottom:8px; border-bottom:2px solid #eaf0fb; }
.fr-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:14px; }
.fr-grid-1 { display:grid; grid-template-columns:1fr; gap:14px; }
.fr-field label { display:block; font-size:0.85rem; font-weight:600; color:#333; margin-bottom:5px; }
.fr-field label .req { color:#e84118; }
.fr-field input, .fr-field select, .fr-field textarea {
    width:100%; padding:11px 13px; border:1px solid #ddd; border-radius:8px;
    font-size:0.9rem; font-family:'Inter',sans-serif; transition:border-color 0.2s; box-sizing:border-box;
}
.fr-field input:focus, .fr-field select:focus, .fr-field textarea:focus {
    border-color:#1a4fa0; outline:none; box-shadow:0 0 0 3px rgba(26,79,160,0.1);
}
.fr-field textarea { resize:vertical; min-height:60px; }

/* Plan cards */
.fr-plans { display:grid; grid-template-columns:repeat(3,1fr); gap:14px; margin-top:10px; }
@media (max-width:640px) { .fr-plans { grid-template-columns:1fr; } }
.fr-plan { padding:20px; border:2px solid #e0e0e0; border-radius:12px; cursor:pointer; transition:all 0.2s; position:relative; text-align:center; }
.fr-plan:hover { border-color:#1a4fa0; transform:translateY(-2px); box-shadow:0 4px 16px rgba(0,0,0,0.08); }
.fr-plan input { display:none; }
.fr-plan.selected { border-color:#1a4fa0; background:#f0f6ff; box-shadow:0 4px 16px rgba(26,79,160,0.15); }
.fr-plan-name { font-family:'Poppins',sans-serif; font-weight:700; font-size:1.1rem; color:#0d2b6e; }
.fr-plan-price { font-size:1.6rem; font-weight:700; color:#1a4fa0; margin:6px 0; }
.fr-plan-original { font-size:0.9rem; color:#999; text-decoration:line-through; }
.fr-plan-discount { display:inline-block; background:#e84118; color:#fff; padding:2px 8px; border-radius:10px; font-size:0.72rem; font-weight:600; margin-left:4px; }
.fr-plan-features { font-size:0.76rem; color:#666; line-height:1.6; text-align:left; margin-top:10px; }
.fr-plan-trusted { position:absolute; top:-10px; left:50%; transform:translateX(-50%); background:#f39c12; color:#fff; padding:3px 14px; border-radius:20px; font-size:0.7rem; font-weight:700; white-space:nowrap; }

/* Captcha */
.fr-captcha-box { display:flex; align-items:center; gap:10px; }
.fr-captcha-code { background:#f0f0f0; border:1px solid #ddd; border-radius:8px; padding:11px 16px; font-family:monospace; font-size:1.2rem; font-weight:700; color:#0d2b6e; letter-spacing:2px; user-select:none; }

/* Payment mode */
.fr-payment { display:none; margin-top:16px; padding:16px; background:#fff8e1; border:1px solid #f39c12; border-radius:10px; }
.fr-payment.active { display:block; }
.fr-pay-options { display:flex; gap:10px; flex-wrap:wrap; margin-top:10px; }
.fr-pay-option { flex:1; min-width:120px; padding:12px; border:2px solid #e0e0e0; border-radius:8px; cursor:pointer; text-align:center; transition:all 0.2s; }
.fr-pay-option:hover { border-color:#1a4fa0; }
.fr-pay-option.selected { border-color:#27ae60; background:#eafaf1; }
.fr-pay-option input { display:none; }
.fr-pay-option-icon { font-size:1.5rem; }
.fr-pay-option-label { font-weight:600; font-size:0.85rem; color:#333; margin-top:4px; }
.fr-pay-option-desc { font-size:0.72rem; color:#999; margin-top:2px; }

.fr-upi-info { margin-top:14px; padding:14px; background:#eafaf1; border-radius:8px; font-size:0.85rem; }
.fr-upi-info strong { color:#16a085; }

.fr-btn { width:100%; padding:16px; background:linear-gradient(135deg,#1a4fa0,#0d2b6e); color:#fff; border:none; border-radius:10px; font-size:1.05rem; font-weight:600; cursor:pointer; font-family:'Poppins',sans-serif; transition:transform 0.2s,box-shadow 0.2s; margin-top:10px; }
.fr-btn:hover { transform:translateY(-1px); box-shadow:0 6px 20px rgba(26,79,160,0.3); }
.fr-alert { padding:12px 16px; border-radius:8px; margin-bottom:20px; font-size:0.9rem; }
.fr-alert-error { background:#fff5f5; color:#c0392b; border:1px solid #f5c6cb; }
.fr-alert-success { background:#eafaf1; color:#1e7e34; border:1px solid #c3e6cb; }
.fr-info { background:#eaf0fb; border-left:4px solid #1a4fa0; padding:14px 18px; border-radius:6px; margin-bottom:20px; font-size:0.85rem; color:#0d2b6e; }
@media (max-width:576px) { .fr-card { padding:24px 18px; } .fr-header h1 { font-size:1.5rem; } }
</style>

<section class="fr-reg">
    <div class="fr-wrap">
        <div class="fr-header">
            <h1>Open a Gmind Institute Franchise</h1>
            <p>Join India's growing computer education network. Choose a plan that fits you.</p>
        </div>

        <div class="fr-card">
            <?php if (!empty($flash_error)): ?>
                <div class="fr-alert fr-alert-error"><?= htmlspecialchars($flash_error, ENT_QUOTES, 'UTF-8') ?></div>
            <?php endif; ?>
            <?php if (!empty($flash_success)): ?>
                <div class="fr-alert fr-alert-success"><?= htmlspecialchars($flash_success, ENT_QUOTES, 'UTF-8') ?></div>
            <?php endif; ?>

            <form method="POST" action="<?= $bp ?>/branch/register" enctype="multipart/form-data" id="franchiseForm">
                <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken, ENT_QUOTES, 'UTF-8') ?>">

                <!-- Center Information -->
                <div class="fr-section">
                    <h3>Center Information</h3>
                    <div class="fr-grid">
                        <div class="fr-field">
                            <label>Center Name <span class="req">*</span></label>
                            <input type="text" name="center_name" required value="<?= htmlspecialchars($_POST['center_name'] ?? '', ENT_QUOTES, 'UTF-8') ?>" placeholder="e.g. ABC Computer Education">
                        </div>
                        <div class="fr-field">
                            <label>Owner Name <span class="req">*</span></label>
                            <input type="text" name="name" required value="<?= htmlspecialchars($_POST['name'] ?? '', ENT_QUOTES, 'UTF-8') ?>" placeholder="Your full name">
                        </div>
                        <div class="fr-field">
                            <label>Contact Number <span class="req">*</span></label>
                            <input type="tel" name="phone" required value="<?= htmlspecialchars($_POST['phone'] ?? '', ENT_QUOTES, 'UTF-8') ?>" placeholder="9876543210" pattern="[0-9+\-\s]{10,15}">
                        </div>
                        <div class="fr-field">
                            <label>Email <span class="req">*</span></label>
                            <input type="email" name="email" required value="<?= htmlspecialchars($_POST['email'] ?? '', ENT_QUOTES, 'UTF-8') ?>" placeholder="you@example.com">
                        </div>
                    </div>
                </div>

                <!-- Location -->
                <div class="fr-section">
                    <h3>Location</h3>
                    <div class="fr-grid">
                        <div class="fr-field">
                            <label>State <span class="req">*</span></label>
                            <select name="state" id="stateSelect" required>
                                <option value="">— Select State —</option>
                                <?php foreach (array_keys($indianStates) as $state): ?>
                                    <option value="<?= htmlspecialchars($state, ENT_QUOTES, 'UTF-8') ?>" <?= ($_POST['state'] ?? '') === $state ? 'selected' : '' ?>><?= htmlspecialchars($state, ENT_QUOTES, 'UTF-8') ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="fr-field">
                            <label>District <span class="req">*</span></label>
                            <select name="city" id="districtSelect" required disabled>
                                <option value="">— Select District —</option>
                            </select>
                        </div>
                        <div class="fr-field">
                            <label>Pincode <span class="req">*</span></label>
                            <input type="text" name="pincode" required value="<?= htmlspecialchars($_POST['pincode'] ?? '', ENT_QUOTES, 'UTF-8') ?>" placeholder="226001" pattern="[0-9]{6}" maxlength="6">
                        </div>
                    </div>
                    <div class="fr-grid-1" style="margin-top:10px;">
                        <div class="fr-field">
                            <label>Center Address <span class="req">*</span></label>
                            <textarea name="address" required rows="2" placeholder="Complete address with landmark"><?= htmlspecialchars($_POST['address'] ?? '', ENT_QUOTES, 'UTF-8') ?></textarea>
                        </div>
                    </div>
                </div>

                <!-- Plan Selection -->
                <div class="fr-section">
                    <h3>Choose Your Plan</h3>
                    <div class="fr-plans">
                        <?php foreach ($plans as $p):
                            $isSelected = ($_POST['plan_id'] ?? '') == $p['id'];
                            $hasDiscount = !empty($p['original_price']) && (float)$p['original_price'] > (float)$p['price'];
                            $discountPct = $hasDiscount ? round(100 - ((float)$p['price'] / (float)$p['original_price'] * 100)) : 0;
                        ?>
                        <label class="fr-plan <?= $isSelected ? 'selected' : '' ?>" onclick="selectPlan(<?= (int)$p['id'] ?>, <?= (int)$p['price'] ?>)">
                            <?php if (!empty($p['is_trusted'])): ?>
                                <span class="fr-plan-trusted">⭐ TRUSTED</span>
                            <?php endif; ?>
                            <input type="radio" name="plan_id" value="<?= (int)$p['id'] ?>" <?= $isSelected ? 'checked' : '' ?>>
                            <div class="fr-plan-name"><?= htmlspecialchars($p['name'], ENT_QUOTES, 'UTF-8') ?></div>
                            <?php if ((float)$p['price'] == 0): ?>
                                <div class="fr-plan-price">FREE</div>
                                <div class="fr-plan-original">&nbsp;</div>
                            <?php else: ?>
                                <div class="fr-plan-price">&#8377;<?= number_format((float)$p['price'], 0) ?></div>
                                <?php if ($hasDiscount): ?>
                                    <div><span class="fr-plan-original">&#8377;<?= number_format((float)$p['original_price'], 0) ?></span> <span class="fr-plan-discount"><?= $discountPct ?>% OFF</span></div>
                                <?php endif; ?>
                            <?php endif; ?>
                            <div class="fr-plan-features">
                                <?php
                                $feats = explode(';', $p['features'] ?? '');
                                foreach ($feats as $feat) {
                                    $feat = trim($feat);
                                    if ($feat) echo '✓ ' . htmlspecialchars($feat, ENT_QUOTES, 'UTF-8') . '<br>';
                                }
                                ?>
                            </div>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Payment Mode (hidden for Free plan, shown for Silver/Gold) -->
                <div class="fr-payment" id="paymentSection">
                    <h3 style="margin:0 0 10px;font-size:1rem;color:#0d2b6e;">Payment Mode</h3>
                    <p style="margin:0 0 10px;font-size:0.82rem;color:#666;">Select how you want to pay. Your application will be reviewed after payment verification.</p>
                    <div class="fr-pay-options">
                        <label class="fr-pay-option" onclick="selectPayMode('upi', this)">
                            <input type="radio" name="payment_mode" value="upi">
                            <div class="fr-pay-option-icon">📱</div>
                            <div class="fr-pay-option-label">UPI</div>
                            <div class="fr-pay-option-desc">Instant via UPI</div>
                        </label>
                        <label class="fr-pay-option" onclick="selectPayMode('online', this)">
                            <input type="radio" name="payment_mode" value="online">
                            <div class="fr-pay-option-icon">💳</div>
                            <div class="fr-pay-option-label">Online</div>
                            <div class="fr-pay-option-desc">Card / NetBanking</div>
                        </label>
                        <label class="fr-pay-option" onclick="selectPayMode('offline', this)">
                            <input type="radio" name="payment_mode" value="offline">
                            <div class="fr-pay-option-icon">🏦</div>
                            <div class="fr-pay-option-label">Offline</div>
                            <div class="fr-pay-option-desc">Cash / Bank Visit</div>
                        </label>
                    </div>
                    <div class="fr-upi-info" id="upiInfo" style="display:none;">
                        <strong>Pay via UPI:</strong> <?= htmlspecialchars($upiId, ENT_QUOTES, 'UTF-8') ?> (<?= htmlspecialchars($upiName, ENT_QUOTES, 'UTF-8') ?>)<br>
                        <strong>Or call:</strong> <?= htmlspecialchars($paymentPhone, ENT_QUOTES, 'UTF-8') ?> for payment assistance<br><br>
                        <label style="font-size:0.82rem;font-weight:600;color:#333;">Upload Payment Screenshot:</label><br>
                        <input type="file" name="payment_screenshot" accept="image/jpeg,image/png" style="font-size:0.8rem;margin-top:4px;">
                    </div>
                </div>

                <!-- Captcha -->
                <div class="fr-section">
                    <h3>Verify You're Human</h3>
                    <div class="fr-field">
                        <label>Solve: <span class="req">*</span></label>
                        <div class="fr-captcha-box">
                            <div class="fr-captcha-code"><?= $_SESSION['franchise_captcha_text'] ?? '? + ? = ?' ?></div>
                            <input type="number" name="captcha" required placeholder="Your answer" style="flex:1;" min="0" max="99">
                        </div>
                    </div>
                </div>

                <button type="submit" class="fr-btn">Submit Application</button>
            </form>

            <div style="text-align:center; margin-top:20px; font-size:0.85rem; color:#999;">
                Already have a branch? <a href="<?= $bp ?>/branch/login" style="color:#1a4fa0;text-decoration:none;font-weight:600;">Login here</a>
            </div>
        </div>
    </div>
</section>

<script>
// Indian districts data (passed from PHP)
var indianStates = <?= json_encode($indianStates, JSON_UNESCAPED_UNICODE) ?>;

// State → District dependent dropdown
document.getElementById('stateSelect').addEventListener('change', function() {
    var state = this.value;
    var districtSelect = document.getElementById('districtSelect');
    districtSelect.innerHTML = '<option value="">— Select District —</option>';
    if (state && indianStates[state]) {
        indianStates[state].forEach(function(d) {
            var opt = document.createElement('option');
            opt.value = d;
            opt.textContent = d;
            districtSelect.appendChild(opt);
        });
        districtSelect.disabled = false;
    } else {
        districtSelect.disabled = true;
    }
});

// Pre-select district if form was submitted with errors
<?php if (!empty($_POST['state']) && !empty($_POST['city'])): ?>
    var savedState = <?= json_encode($_POST['state']) ?>;
    var savedDistrict = <?= json_encode($_POST['city']) ?>;
    if (indianStates[savedState]) {
        var districtSelect = document.getElementById('districtSelect');
        districtSelect.innerHTML = '<option value="">— Select District —</option>';
        indianStates[savedState].forEach(function(d) {
            var opt = document.createElement('option');
            opt.value = d;
            opt.textContent = d;
            if (d === savedDistrict) opt.selected = true;
            districtSelect.appendChild(opt);
        });
        districtSelect.disabled = false;
    }
<?php endif; ?>

// Plan selection → show/hide payment section
function selectPlan(planId, price) {
    document.querySelectorAll('.fr-plan').forEach(function(el) { el.classList.remove('selected'); });
    event.currentTarget.classList.add('selected');
    var paySection = document.getElementById('paymentSection');
    if (price > 0) {
        paySection.classList.add('active');
    } else {
        paySection.classList.remove('active');
    }
}

// Payment mode selection
function selectPayMode(mode, el) {
    document.querySelectorAll('.fr-pay-option').forEach(function(e) { e.classList.remove('selected'); });
    el.classList.add('selected');
    var upiInfo = document.getElementById('upiInfo');
    if (mode === 'upi') {
        upiInfo.style.display = 'block';
    } else {
        upiInfo.style.display = 'none';
    }
}
</script>
