<?php

namespace App\Repositories;

use App\Config\ContextDB;
use App\Models\Client;
use PDO;

class ClientRepository {

    private PDO $context;

    public function __construct() {
        $this->context = (new ContextDB())->conn;
    }

    public function getAll(): array 
    {
        $consult = $this->context->prepare("SELECT * FROM clients");
        $consult->execute();
        $response = $consult->fetchAll(PDO::FETCH_ASSOC);
        $response = array_map(fn($item) => new Client($item), $response);
        return $response;
    }

    public function findBy(string $columnName, string $value): Client
    {
        $consult = $this->context->prepare("
            SELECT * FROM clients WHERE $columnName = :value
        ");

        $consult->execute([
            "value" => $value
        ]);

        $response = $consult->fetch(PDO::FETCH_ASSOC);

        return new Client([
            "id" => $response["id"],
            "name_company" => $response["name_company"],
            "name_contact" => $response["name_contact"],
            "phone_contact" => $response["phone_contact"],
            "email_contact" => $response["email_contact"]
        ]);
    }

    public function create(Client $client): int
    {
        $consult = $this->context->prepare("
            INSERT INTO clients(name_company, name_contact, phone_contact, email_contact)
            VALUES (:name_company, :name_contact, :phone_contact, :email_contact)
        ");

        $consult->execute([
            "name_company" => $client->name_company,
            "name_contact" => $client->name_contact,
            "phone_contact" => $client->phone_contact,
            "email_contact" => $client->email_contact
        ]);

        return $this->context->lastInsertId();
    }

    public function update(Client $client): bool
    {
        $consult = $this->context->prepare("
            UPDATE clients
            SET name_company = :name_company,
                name_contact = :name_contact,
                phone_contact = :phone_contact,
                email_contact = :email_contact
            WHERE id = :id
        ");
        

        $consult->execute([
            "name_company" => $client->name_company,
            "name_contact" => $client->name_contact,
            "phone_contact" => $client->phone_contact,
            "email_contact" => $client->email_contact,
            "id" => $client->id
        ]);

        return $consult->rowCount() === 1;
    }

    public function changeStatus(int $clientId): bool
    {
        $consult = $this->context->prepare("
            UPDATE clients
            SET isActive = !isActive
            WHERE id = :ClientId
        ");

        $consult->execute([
            "ClientId" => $clientId
        ]);

        return $consult->rowCount() === 1;
    }
}