<?php

declare(strict_types=1);

namespace BranchAdmin\Controllers;

/**
 * Branch Application Controller (Public)
 *
 * Handles the public-facing franchise application form at /branch/register.
 * - Free plan → auto-approved instantly, branch created, password emailed
 * - Silver/Gold plan → application saved, payment verification required
 *
 * Captcha is validated for public submissions (not for Super Admin submissions).
 */
class BranchApplicationController extends BranchBaseController
{
    /**
     * Display the franchise application form.
     */
    public function form(): void
    {
        if (isBranchAdmin()) {
            redirect(BASE_PATH . '/branch/dashboard');
        }

        // Fetch franchise plans
        $plans = [];
        try {
            $stmt = $this->db->query("SELECT * FROM `franchise_plans` WHERE `is_active` = 1 ORDER BY `price` ASC");
            $plans = $stmt->fetchAll() ?: [];
        } catch (\Throwable $e) {}

        // Fetch payment settings
        $upiId = 'gmind@upi';
        $upiName = 'Gmind Institute';
        $paymentPhone = '9305640290';
        try {
            $settingModel = new \App\Models\Setting($this->db);
            $upiId = $settingModel->get('payment_upi_id') ?: $upiId;
            $upiName = $settingModel->get('payment_upi_name') ?: $upiName;
            $paymentPhone = $settingModel->get('payment_phone') ?: $paymentPhone;
        } catch (\Throwable $e) {}

        // Generate captcha
        if (session_status() === PHP_SESSION_NONE) { session_start(); }
        $a = rand(1, 9);
        $b = rand(1, 9);
        $_SESSION['franchise_captcha'] = $a + $b;
        $_SESSION['franchise_captcha_text'] = "{$a} + {$b} = ?";

        // Render using website header/footer
        $csrfToken = generateCsrfToken();
        $flash_error   = flash('error');
        $flash_success = flash('success');
        $basePath      = defined('BASE_PATH') ? BASE_PATH : '/gmind';
        $settings      = [];
        $currentPage   = 'branch-register';
        $title         = 'Open a Gmind Institute Franchise - Gmind Institute';

        try {
            $settingModel = new \App\Models\Setting($this->db);
            $settings = $settingModel->getAll();
        } catch (\Throwable $e) {}

        require APP_ROOT . '/app/Views/layouts/header.php';

        extract([
            'plans'         => $plans,
            'csrfToken'     => $csrfToken,
            'flash_error'   => $flash_error,
            'flash_success' => $flash_success,
            'basePath'      => $basePath,
            'upiId'         => $upiId,
            'upiName'       => $upiName,
            'paymentPhone'  => $paymentPhone,
        ]);
        require APP_ROOT . '/app/Views/branch/register.php';

        require APP_ROOT . '/app/Views/layouts/footer.php';
        exit;
    }

    /**
     * Process the franchise application submission.
     */
    public function submit(): void
    {
        $this->validateCsrf();

        $centerName = trim($_POST['center_name'] ?? '');
        $name       = trim($_POST['name'] ?? '');
        $email      = trim($_POST['email'] ?? '');
        $phone      = trim($_POST['phone'] ?? '');
        $state      = trim($_POST['state'] ?? '');
        $district   = trim($_POST['city'] ?? ''); // 'city' field stores the district
        $pincode    = trim($_POST['pincode'] ?? '');
        $address    = trim($_POST['address'] ?? '');
        $planId     = (int) ($_POST['plan_id'] ?? 0);
        $paymentMode = trim($_POST['payment_mode'] ?? 'free');
        $captcha    = trim($_POST['captcha'] ?? '');

        // Validation
        if (empty($centerName) || empty($name) || empty($email) || empty($phone) || empty($state) || empty($district) || empty($pincode) || empty($address)) {
            flash('error', 'Please fill in all required fields.');
            redirect(BASE_PATH . '/branch/register');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            flash('error', 'Please enter a valid email address.');
            redirect(BASE_PATH . '/branch/register');
        }

        if (!preg_match('/^[0-9]{6}$/', $pincode)) {
            flash('error', 'Please enter a valid 6-digit pincode.');
            redirect(BASE_PATH . '/branch/register');
        }

        // Captcha validation
        if (session_status() === PHP_SESSION_NONE) { session_start(); }
        $expectedCaptcha = $_SESSION['franchise_captcha'] ?? 0;
        if ((int) $captcha !== (int) $expectedCaptcha) {
            flash('error', 'Captcha answer is incorrect. Please try again.');
            redirect(BASE_PATH . '/branch/register');
        }

        if ($planId <= 0) {
            flash('error', 'Please select a plan.');
            redirect(BASE_PATH . '/branch/register');
        }

        // Fetch the selected plan
        $stmt = $this->db->prepare("SELECT * FROM `franchise_plans` WHERE `id` = :pid AND `is_active` = 1 LIMIT 1");
        $stmt->execute([':pid' => $planId]);
        $plan = $stmt->fetch() ?: null;
        if (!$plan) {
            flash('error', 'Invalid plan selected.');
            redirect(BASE_PATH . '/branch/register');
        }

        $isFree = (float) $plan['price'] === 0.00;

        // For paid plans, validate payment mode
        if (!$isFree) {
            if (!in_array($paymentMode, ['upi', 'online', 'offline'], true)) {
                flash('error', 'Please select a payment mode.');
                redirect(BASE_PATH . '/branch/register');
            }
        } else {
            $paymentMode = 'free';
        }

        // Check if email already exists in applications
        $stmt = $this->db->prepare("SELECT id, status FROM `branch_applications` WHERE `email` = :email ORDER BY `created_at` DESC LIMIT 1");
        $stmt->execute([':email' => $email]);
        $existing = $stmt->fetch();
        if ($existing && $existing['status'] === 'pending') {
            flash('error', 'You already have a pending application. Our team will contact you soon.');
            redirect(BASE_PATH . '/branch/register');
        }
        if ($existing && $existing['status'] === 'approved') {
            flash('info', 'Your application was already approved. Please login at /branch/login');
            redirect(BASE_PATH . '/branch/login');
        }

        // Check email uniqueness in users table
        $stmt = $this->db->prepare("SELECT id FROM `users` WHERE `email` = :email LIMIT 1");
        $stmt->execute([':email' => $email]);
        if ($stmt->fetch()) {
            flash('error', "A user with email '{$email}' already exists in our system.");
            redirect(BASE_PATH . '/branch/register');
        }

        // Handle payment screenshot upload (for paid plans)
        $paymentScreenshot = null;
        if (!$isFree && $paymentMode === 'upi') {
            $paymentScreenshot = $this->handleImageUpload('payment_screenshot', 'payment_proofs');
        }

        // Generate branch code (GMBRxx — auto-incremented)
        $branchCode = $this->generateNextBranchCode();

        // Default password for Free plan = 123456
        $defaultPassword = '123456';

        try {
            if ($isFree) {
                // ─── FREE PLAN: Auto-approve + create branch + create user + send email ───
                $this->db->beginTransaction();

                // 1. Create branch
                $referralCode = 'REF-' . $branchCode;
                $stmt = $this->db->prepare(
                    "INSERT INTO `branches`
                        (`name`, `branch_code`, `city`, `state`, `address`, `phone`,
                         `owner_name`, `owner_email`, `owner_phone`, `plan_id`,
                         `pincode`, `wallet_balance`, `referral_code`, `status`,
                         `kyc_status`, `affiliation_status`, `is_verified`, `is_trusted`,
                         `approved_at`, `approved_by`, `created_at`, `updated_at`)
                     VALUES
                        (:name, :bc, :city, :state, :addr, :phone,
                         :owner, :email, :phone, :plan_id,
                         :pincode, 0.00, :ref, 'active',
                         'pending', 'pending', 1, :trusted,
                         NOW(), NULL, NOW(), NOW())"
                );
                $stmt->execute([
                    ':name'    => $centerName,
                    ':bc'      => $branchCode,
                    ':city'    => $district,
                    ':state'   => $state,
                    ':addr'    => $address,
                    ':phone'   => $phone,
                    ':owner'   => $name,
                    ':email'   => $email,
                    ':plan_id' => $planId,
                    ':pincode' => $pincode,
                    ':ref'     => $referralCode,
                    ':trusted' => !empty($plan['is_trusted']) ? 1 : 0,
                ]);
                $branchId = (int) $this->db->lastInsertId();

                // 2. Create branch_admin user
                $hashedPassword = password_hash($defaultPassword, PASSWORD_DEFAULT);
                $stmt = $this->db->prepare(
                    "INSERT INTO `users`
                        (`name`, `email`, `password`, `role`, `phone`, `branch_id`, `branch_code`,
                         `is_active`, `status`, `created_at`, `updated_at`)
                     VALUES
                        (:name, :email, :pwd, 'branch_admin', :phone, :bid, :bcode,
                         1, 'active', NOW(), NOW())"
                );
                $stmt->execute([
                    ':name'  => $name,
                    ':email' => $email,
                    ':pwd'   => $hashedPassword,
                    ':phone' => $phone,
                    ':bid'   => $branchId,
                    ':bcode' => $branchCode,
                ]);
                $userId = (int) $this->db->lastInsertId();

                // 3. Link admin_user_id
                $this->db->prepare("UPDATE `branches` SET `admin_user_id` = :uid WHERE `id` = :bid")
                    ->execute([':uid' => $userId, ':bid' => $branchId]);

                // 4. Save application record (approved)
                $stmt = $this->db->prepare(
                    "INSERT INTO `branch_applications`
                        (`name`, `center_name`, `email`, `phone`, `city`, `state`, `district`,
                         `pincode`, `address`, `plan_id`, `investment_range`,
                         `payment_mode`, `payment_status`, `payment_transaction_ref`,
                         `status`, `admin_notes`, `reviewed_at`, `reviewed_by`, `created_at`, `updated_at`)
                     VALUES
                        (:name, :cname, :email, :phone, :city, :state, :district,
                         :pincode, :addr, :plan_id, NULL,
                         'free', 'free', NULL,
                         'approved', :notes, NOW(), NULL, NOW(), NOW())"
                );
                $stmt->execute([
                    ':name'     => $name,
                    ':cname'    => $centerName,
                    ':email'    => $email,
                    ':phone'    => $phone,
                    ':city'     => $district,
                    ':state'    => $state,
                    ':district' => $district,
                    ':pincode'  => $pincode,
                    ':addr'     => $address,
                    ':plan_id'  => $planId,
                    ':notes'    => "Auto-approved (Free plan). Branch {$branchCode} created. Password: {$defaultPassword}",
                ]);

                $this->db->commit();

                // 5. ✅ Send welcome email with login details (using new EmailHelper)
                $emailSent = false;
                $emailError = '';
                try {
                    $helper = new \App\Helpers\EmailHelper($this->db);
                    if ($helper->isConfigured()) {
                        $loginUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . (defined('BASE_PATH') ? BASE_PATH : '/gmind') . '/branch/login';
                        $subject = "Your Gmind Branch is Ready! Login: {$branchCode}";
                        $body = $this->buildFranchiseWelcomeEmailHtml([
                            'name'           => $name,
                            'center_name'    => $centerName,
                            'branch_code'    => $branchCode,
                            'plan_name'      => $plan['name'] ?? 'Free',
                            'email'          => $email,
                            'password'       => $defaultPassword,
                            'login_url'      => $loginUrl,
                            'city'           => $district,
                            'state'          => $state,
                        ]);
                        $emailSent = $helper->send($email, $name, $subject, $body);
                        if (!$emailSent) {
                            $emailError = $helper->getLastError();
                        }
                    } else {
                        $emailError = 'SMTP not configured';
                    }
                } catch (\Throwable $e) {
                    $emailError = $e->getMessage();
                    error_log('Free plan welcome email failed: ' . $e->getMessage());
                }

                $successMsg = "🎉 Your branch is ready! Branch Code: {$branchCode}. Login at /branch/login with email: {$email}, password: {$defaultPassword}.";
                if ($emailSent) {
                    $successMsg .= " 📧 We've sent these details to your email.";
                } else {
                    $successMsg .= " ⚠️ Email not sent ({$emailError}). Please save these login details.";
                }
                flash('success', $successMsg);

            } else {
                // ─── PAID PLAN (Silver/Gold): Save application, pending payment verification ───
                $paymentStatus = ($paymentMode === 'offline') ? 'pending' : 'pending';

                $stmt = $this->db->prepare(
                    "INSERT INTO `branch_applications`
                        (`name`, `center_name`, `email`, `phone`, `city`, `state`, `district`,
                         `pincode`, `address`, `plan_id`, `investment_range`,
                         `payment_mode`, `payment_status`, `payment_screenshot`,
                         `status`, `admin_notes`, `created_at`, `updated_at`)
                     VALUES
                        (:name, :cname, :email, :phone, :city, :state, :district,
                         :pincode, :addr, :plan_id, NULL,
                         :pmode, 'pending', :screenshot,
                         'pending', :notes, NOW(), NOW())"
                );
                $stmt->execute([
                    ':name'       => $name,
                    ':cname'      => $centerName,
                    ':email'      => $email,
                    ':phone'      => $phone,
                    ':city'       => $district,
                    ':state'      => $state,
                    ':district'   => $district,
                    ':pincode'    => $pincode,
                    ':addr'       => $address,
                    ':plan_id'    => $planId,
                    ':pmode'      => $paymentMode,
                    ':screenshot' => $paymentScreenshot,
                    ':notes'      => "Applied for {$plan['name']} plan (₹{$plan['price']}). Payment mode: {$paymentMode}. Branch code will be: {$branchCode}",
                ]);

                flash('success', "Application submitted! Plan: {$plan['name']} (₹" . number_format((float)$plan['price'], 0) . "). Payment mode: {$paymentMode}. Our team will verify your payment and activate your branch within 24 hours. For help, call {$paymentPhone}.");
            }
        } catch (\Throwable $e) {
            if (isset($this->db) && $this->db->inTransaction()) {
                $this->db->rollBack();
            }
            error_log('Branch application submit failed: ' . $e->getMessage());
            error_log('Stack: ' . $e->getTraceAsString());
            // Show the actual error to help debug (remove in production later)
            flash('error', 'Error: ' . $e->getMessage() . ' — Please contact support with this message.');
        }
        redirect(BASE_PATH . '/branch/register');
    }

    /**
     * Generate the next sequential branch code (GMBRxx).
     */
    private function generateNextBranchCode(): string
    {
        try {
            $stmt = $this->db->query(
                "SELECT `branch_code` FROM `branches`
                 WHERE `branch_code` LIKE 'GMBR%'
                 ORDER BY CAST(SUBSTRING(`branch_code`, 5) AS UNSIGNED) DESC
                 LIMIT 1"
            );
            $last = $stmt->fetch();
            if ($last && !empty($last['branch_code'])) {
                $num = (int) substr($last['branch_code'], 4);
                return 'GMBR' . str_pad($num + 1, 2, '0', STR_PAD_LEFT);
            }
        } catch (\Throwable $e) {}
        return 'GMBR02';
    }

    /**
     * Build HTML email body for franchise welcome (free plan auto-approval).
     */
    private function buildFranchiseWelcomeEmailHtml(array $data): string
    {
        $name        = htmlspecialchars($data['name'] ?? '', ENT_QUOTES);
        $centerName  = htmlspecialchars($data['center_name'] ?? '', ENT_QUOTES);
        $branchCode  = htmlspecialchars($data['branch_code'] ?? '', ENT_QUOTES);
        $planName    = htmlspecialchars($data['plan_name'] ?? 'Free', ENT_QUOTES);
        $email       = htmlspecialchars($data['email'] ?? '', ENT_QUOTES);
        $password    = htmlspecialchars($data['password'] ?? '', ENT_QUOTES);
        $loginUrl    = htmlspecialchars($data['login_url'] ?? '', ENT_QUOTES);
        $city        = htmlspecialchars($data['city'] ?? '', ENT_QUOTES);
        $state       = htmlspecialchars($data['state'] ?? '', ENT_QUOTES);

        return <<<HTML
<!DOCTYPE html>
<html><head><meta charset="UTF-8"></head>
<body style="margin:0;padding:0;font-family:'Segoe UI',Arial,sans-serif;background:#f3f4f6;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f3f4f6;padding:20px;">
    <tr><td align="center">
      <table width="600" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
        <tr><td style="background:linear-gradient(135deg,#16a085,#117a65);padding:24px 32px;text-align:center;">
          <h1 style="margin:0;color:#fff;font-size:1.6rem;">GMIND INSTITUTE</h1>
          <p style="margin:6px 0 0;color:rgba(255,255,255,0.9);font-size:0.88rem;">Your Branch is Ready!</p>
        </td></tr>
        <tr><td style="padding:32px;">
          <h2 style="margin:0 0 16px;color:#2c1e4a;font-size:1.3rem;">🎉 Congratulations, {$name}!</h2>
          <p style="margin:0 0 16px;color:#4b5563;font-size:0.95rem;line-height:1.6;">
            Your Gmind Institute franchise application has been <strong>auto-approved</strong> (Free plan). Your branch is now active and ready to use!
          </p>
          <table width="100%" cellpadding="12" cellspacing="0" style="border:1px solid #e5e7eb;border-radius:8px;margin:16px 0;">
            <tr style="background:#f8f4ff;"><td style="color:#6c3fe8;font-weight:600;font-size:0.85rem;">Center Name</td><td style="color:#2c1e4a;font-weight:700;">{$centerName}</td></tr>
            <tr><td style="color:#6c3fe8;font-weight:600;font-size:0.85rem;border-top:1px solid #e5e7eb;">Branch Code</td><td style="color:#2c1e4a;font-weight:700;font-family:monospace;border-top:1px solid #e5e7eb;">{$branchCode}</td></tr>
            <tr><td style="color:#6c3fe8;font-weight:600;font-size:0.85rem;border-top:1px solid #e5e7eb;">Location</td><td style="color:#2c1e4a;border-top:1px solid #e5e7eb;">{$city}, {$state}</td></tr>
            <tr><td style="color:#6c3fe8;font-weight:600;font-size:0.85rem;border-top:1px solid #e5e7eb;">Plan</td><td style="color:#2c1e4a;border-top:1px solid #e5e7eb;">{$planName}</td></tr>
          </table>
          <div style="background:#fef3c7;border-left:4px solid #d97706;padding:14px 18px;border-radius:6px;margin:20px 0;">
            <p style="margin:0 0 8px;color:#b45309;font-weight:700;font-size:0.9rem;">🔐 Your Login Credentials</p>
            <p style="margin:0;color:#92400e;font-size:0.88rem;">
              <strong>Login URL:</strong> <a href="{$loginUrl}" style="color:#2563eb;">{$loginUrl}</a><br>
              <strong>Email:</strong> {$email}<br>
              <strong>Password:</strong> {$password}<br>
              <em style="color:#6b7280;font-size:0.8rem;">You can also login using Branch Code: {$branchCode}</em>
            </p>
          </div>
          <p style="margin:16px 0;color:#4b5563;font-size:0.88rem;line-height:1.6;">
            Please login and update your branch profile, add courses, and start admitting students.<br><br>
            Best regards,<br>
            <strong>GMIND Institute Team</strong>
          </p>
        </td></tr>
        <tr><td style="background:#f8f9fa;padding:16px 32px;text-align:center;border-top:1px solid #e5e7eb;">
          <p style="margin:0;color:#9ca3af;font-size:0.75rem;">This is an automated email. Please do not reply.</p>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body></html>
HTML;
    }
}
