<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Branch Model
 *
 * Handles institute branch data with fallback queries for missing columns.
 */
class Branch extends Model
{
    protected string $table = 'branches';

    /**
     * Get latest active branches.
     *
     * @param int $limit Maximum number of branches
     * @return array<int, array<string, mixed>>
     */
    public function getLatest(int $limit = 8): array
    {
        try {
            $sql = sprintf(
                'SELECT * FROM `%s` WHERE `active` = :active ORDER BY `created_at` DESC LIMIT :limit',
                $this->table
            );
            $stmt = $this->db->prepare($sql);
            $stmt->bindValue(':active', 1, PDO::PARAM_INT);
            $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (\Throwable $e) {
            // Fallback: try without created_at column
            try {
                $sql = sprintf('SELECT * FROM `%s` WHERE `active` = :active ORDER BY `id` DESC LIMIT :limit', $this->table);
                $stmt = $this->db->prepare($sql);
                $stmt->bindValue(':active', 1, PDO::PARAM_INT);
                $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
                $stmt->execute();
                return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
            } catch (\Throwable $e2) {
                // Last resort: get all rows
                try {
                    $sql = sprintf('SELECT * FROM `%s` ORDER BY `id` DESC LIMIT :limit', $this->table);
                    $stmt = $this->db->prepare($sql);
                    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
                    $stmt->execute();
                    return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
                } catch (\Throwable $e3) {
                    return [];
                }
            }
        }
    }

    /**
     * Get count of active branches.
     *
     * @return int
     */
    public function getActiveCount(): int
    {
        try {
            $sql = sprintf(
                'SELECT COUNT(*) AS total FROM `%s` WHERE `active` = :active',
                $this->table
            );
            $stmt = $this->db->prepare($sql);
            $stmt->execute([':active' => 1]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return (int) ($result['total'] ?? 0);
        } catch (\Throwable $e) {
            // Fallback: count all
            try {
                return $this->count();
            } catch (\Throwable $e2) {
                return 0;
            }
        }
    }
}
