<?php

namespace Admin\Controllers;

use Admin\Controllers\AdminController;

class AdminBranchApplicationController extends AdminController
{
    /**
     * List all branch franchise applications
     */
    public function index()
    {
        requireAdmin();

        $stmt = $this->db->prepare("
            SELECT ba.*, fp.name AS plan_name, fp.price AS plan_price
            FROM branch_applications ba
            LEFT JOIN franchise_plans fp ON ba.plan_id = fp.id
            ORDER BY ba.created_at DESC
        ");
        $stmt->execute();
        $applications = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        return $this->adminView('branch-applications/index', [
            'applications' => $applications
        ]);
    }

    /**
     * View single application details
     */
    public function show($params)
    {
        requireAdmin();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare("
            SELECT ba.*, fp.name AS plan_name, fp.price AS plan_price, fp.duration_months, fp.max_students, fp.max_exams
            FROM branch_applications ba
            LEFT JOIN franchise_plans fp ON ba.plan_id = fp.id
            WHERE ba.id = :id
        ");
        $stmt->execute(['id' => $id]);
        $application = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$application) {
            flash('error', 'Application not found.');
            redirect(BASE_PATH . '/admin/branch-applications');
            return;
        }

        return $this->adminView('branch-applications/show', [
            'application' => $application
        ]);
    }

    /**
     * Approve a branch application
     */
    public function approve($params)
    {
        requireAdmin();

        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare("SELECT * FROM branch_applications WHERE id = :id AND status = 'pending'");
        $stmt->execute(['id' => $id]);
        $application = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$application) {
            flash('error', 'Application not found or already processed.');
            redirect(BASE_PATH . '/admin/branch-applications');
            return;
        }

        $this->db->beginTransaction();

        try {
            // Update application status
            $stmt = $this->db->prepare("
                UPDATE branch_applications
                SET status = 'approved', reviewed_at = NOW(), reviewed_by = :admin_id
                WHERE id = :id
            ");
            $stmt->execute([
                'admin_id' => $_SESSION['admin_id'] ?? null,
                'id' => $id
            ]);

            // Create branch record
            $stmt = $this->db->prepare("
                INSERT INTO branches (name, branch_code, city, state, address, phone, owner_name, owner_phone, owner_email, wallet_balance, active)
                VALUES (:name, :branch_code, :city, :state, :address, :phone, :owner_name, :owner_phone, :owner_email, 0, 1)
            ");
            $stmt->execute([
                'name'         => $application['branch_name'],
                'branch_code'  => $application['branch_code'],
                'city'         => $application['city'],
                'state'        => $application['state'],
                'address'      => $application['address'],
                'phone'        => $application['phone'],
                'owner_name'   => $application['owner_name'],
                'owner_phone'  => $application['owner_phone'],
                'owner_email'  => $application['owner_email']
            ]);

            $branchId = $this->db->lastInsertId();

            // Create user with role branch_admin
            $stmt = $this->db->prepare("
                INSERT INTO users (name, email, phone, password, role, branch_id, branch_code, is_active, status)
                VALUES (:name, :email, :phone, :password, 'branch_admin', :branch_id, :branch_code, 1, 'active')
            ");

            $defaultPassword = password_hash('ChangeMe@123', PASSWORD_BCRYPT);

            $stmt->execute([
                'name'        => $application['owner_name'],
                'email'       => $application['owner_email'],
                'phone'       => $application['owner_phone'],
                'password'    => $defaultPassword,
                'branch_id'   => $branchId,
                'branch_code' => $application['branch_code']
            ]);

            $this->db->commit();

            flash('success', 'Application approved successfully. Branch and branch admin account created.');
        } catch (\Exception $e) {
            $this->db->rollBack();
            flash('error', 'Failed to approve application: ' . $e->getMessage());
        }

        redirect(BASE_PATH . '/admin/branch-applications');
    }

    /**
     * Reject a branch application
     */
    public function reject($params)
    {
        requireAdmin();

        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);
        $adminNotes = sanitize($_POST['admin_notes'] ?? '');

        $stmt = $this->db->prepare("SELECT * FROM branch_applications WHERE id = :id AND status = 'pending'");
        $stmt->execute(['id' => $id]);
        $application = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$application) {
            flash('error', 'Application not found or already processed.');
            redirect(BASE_PATH . '/admin/branch-applications');
            return;
        }

        $stmt = $this->db->prepare("
            UPDATE branch_applications
            SET status = 'rejected', admin_notes = :admin_notes, reviewed_at = NOW(), reviewed_by = :admin_id
            WHERE id = :id
        ");
        $stmt->execute([
            'admin_notes' => $adminNotes,
            'admin_id'    => $_SESSION['admin_id'] ?? null,
            'id'          => $id
        ]);

        flash('success', 'Application rejected successfully.');
        redirect(BASE_PATH . '/admin/branch-applications');
    }

    /**
     * Delete a branch application
     */
    public function delete($params)
    {
        requireAdmin();

        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare("SELECT id FROM branch_applications WHERE id = :id");
        $stmt->execute(['id' => $id]);
        $application = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$application) {
            flash('error', 'Application not found.');
            redirect(BASE_PATH . '/admin/branch-applications');
            return;
        }

        $stmt = $this->db->prepare("DELETE FROM branch_applications WHERE id = :id");
        $stmt->execute(['id' => $id]);

        flash('success', 'Application deleted successfully.');
        redirect(BASE_PATH . '/admin/branch-applications');
    }
}
