<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class AdminOrganizationsController extends Controller
{
    private $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    /*
    --------------------------------------------------
    Access Control
    --------------------------------------------------
    */

    private function requireAdmin()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (!isset($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        if (!in_array(
            $_SESSION['role'] ?? '',
            ['super_admin','admin']
        )) {
            die("Access denied.");
        }
    }

    /*
    --------------------------------------------------
    List
    --------------------------------------------------
    */

    public function index()
    {
        $this->requireAdmin();

        $stmt = $this->db->query("
            SELECT
                o.*,
                COUNT(DISTINCT c.id) AS conferences,
                COUNT(DISTINCT u.id) AS users,
                COUNT(DISTINCT CASE
                    WHEN c.start_date <= NOW()
                     AND c.end_date >= NOW()
                    THEN c.id
                END) AS current
            FROM organizations o
            LEFT JOIN conferences c
                ON c.org_id = o.id
            LEFT JOIN users u
                ON u.org_id = o.id
            GROUP BY o.id
            ORDER BY o.id DESC
        ");

        $organizations =
            $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $this->render(
            'admin/organizations/index',
            compact('organizations')
        );
    }

    /*
    --------------------------------------------------
    Create
    --------------------------------------------------
    */

    public function create()
    {
        $this->requireAdmin();

        $this->render(
            'admin/organizations/create',
            [
                'title' => 'Create Organization'
            ]
        );
    }

    /*
    --------------------------------------------------
    Store (FIXED + ENHANCED)
    --------------------------------------------------
    */

    public function store()
    {
        $this->requireAdmin();

        /*
        Input
        */

        $name  = trim($_POST['name'] ?? '');
        $email = trim($_POST['contact_email'] ?? '');

        $primary   = $_POST['primary_color'] ?? '#0072ff';
        $secondary = $_POST['secondary_color'] ?? '#00c6ff';
        $theme     = $_POST['theme'] ?? 'default';

        if (!$name) {
            die("Organization name is required");
        }

        /*
        Generate unique code
        */

        $baseCode = strtolower(
            preg_replace('/[^a-zA-Z0-9]+/', '-', $name)
        );

        $code = trim($baseCode, '-');

        if (!$code) {
            $code = 'org';
        }

        $originalCode = $code;
        $i = 1;

        while (true) {

            $stmt = $this->db->prepare("
                SELECT id
                FROM organizations
                WHERE code = ?
                LIMIT 1
            ");

            $stmt->execute([$code]);

            if (!$stmt->fetch()) {
                break;
            }

            $code = $originalCode . '-' . $i;
            $i++;
        }

        /*
        Insert
        */

        $stmt = $this->db->prepare("
            INSERT INTO organizations
            (
                name,
                code,
                contact_email,
                primary_color,
                secondary_color,
                theme,
                is_active,
                created_at
            )
            VALUES
            (?, ?, ?, ?, ?, ?, 1, NOW())
        ");

        $stmt->execute([
            $name,
            $code,
            $email,
            $primary,
            $secondary,
            $theme
        ]);

        header("Location: /easychair/admin/organizations");
        exit;
    }

    /*
    --------------------------------------------------
    Edit
    --------------------------------------------------
    */

    public function edit()
    {
        $this->requireAdmin();

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

        $stmt = $this->db->prepare("
            SELECT *
            FROM organizations
            WHERE id = ?
        ");

        $stmt->execute([$id]);

        $organization =
            $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$organization) {
            die("Organization not found");
        }

        $this->render(
            'admin/organizations/edit',
            compact('organization')
        );
    }

    /*
    --------------------------------------------------
    Update (ENHANCED)
    --------------------------------------------------
    */

    public function update()
    {
        $this->requireAdmin();

        $id    = (int)($_POST['id'] ?? 0);
        $name  = trim($_POST['name'] ?? '');
        $email = trim($_POST['contact_email'] ?? '');

        $primary   = $_POST['primary_color'] ?? '#0072ff';
        $secondary = $_POST['secondary_color'] ?? '#00c6ff';
        $theme     = $_POST['theme'] ?? 'default';

        if (!$id || !$name) {
            die("Invalid data");
        }

        /*
        Update (code remains unchanged)
        */

        $stmt = $this->db->prepare("
            UPDATE organizations
            SET
                name = ?,
                contact_email = ?,
                primary_color = ?,
                secondary_color = ?,
                theme = ?,
                updated_at = NOW()
            WHERE id = ?
        ");

        $stmt->execute([
            $name,
            $email,
            $primary,
            $secondary,
            $theme,
            $id
        ]);

        header("Location: /easychair/admin/organizations");
        exit;
    }

    /*
    --------------------------------------------------
    Delete
    --------------------------------------------------
    */

    public function delete()
    {
        $this->requireAdmin();

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

        if (!$id) {
            die("Invalid ID");
        }

        $stmt = $this->db->prepare("
            DELETE
            FROM organizations
            WHERE id = ?
        ");

        $stmt->execute([$id]);

        header("Location: /easychair/admin/organizations");
        exit;
    }
}
