<?php

namespace App\Models;

use PDO;
use Config\Database;

class ExpedientCounter extends BaseModel
{
    protected static $table = 'expedient_counters';

    public $id;
    public $modality_id;
    public $start_number;
    public $current_number;
    public $created_at;
    public $updated_at;

    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->current_number = $data['current_number'] ?? 1;
    }

    public function save()
    {
        $db = Database::getConnection();
        if ($this->id) {
            $query = "UPDATE expedient_counters 
                    SET modality_id = :modality_id, start_number = :start_number, current_number = :current_number 
                    WHERE id = :id";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':id' => $this->id,
                ':modality_id' => $this->modality_id,
                ':start_number' => $this->start_number,
                ':current_number' => $this->current_number
            ]);
        } else {
            $query = "INSERT INTO expedient_counters (modality_id, start_number, current_number) 
                    VALUES (:modality_id, :start_number, :current_number)";
            $stmt = $db->prepare($query);
            $stmt->execute([
                ':modality_id' => $this->modality_id,
                ':start_number' => $this->start_number,
                ':current_number' => $this->current_number
            ]);
            $this->id = $db->lastInsertId();
        }
    }

    public static function deleteAll()
    {
        $db = Database::getConnection();
        $query = "DELETE FROM expedient_counters";
        $stmt = $db->prepare($query);
        $stmt->execute();
    }

}