<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * Branch Model
 *
 * Handles institute branch locations data retrieval.
 */
class Branch extends Model
{
    /**
     * The database table associated with the model.
     */
    protected string $table = 'branches';

    /**
     * Get the latest active branches ordered by created_at DESC with a limit.
     *
     * @param int $limit Maximum number of branches to return
     * @return array<int, array<string, mixed>>
     */
    public function getLatest(int $limit = 8): array
    {
        $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) ?: [];
    }

    /**
     * Get the count of active branches.
     *
     * @return int
     */
    public function getActiveCount(): int
    {
        $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);
    }
}
