<?php

require_once __DIR__ . '/../database/database.php';

class proveedorModel {

    private PDO $db;

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

    // LISTAR PROVEEDORES

    public function listarProveedores(): array {
        
        $sql = "SELECT id, razon_social, telefono, email from proveedores ORDER BY id ASC";

        $stmt = $this->db->prepare($sql);

        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // CREAR PROVEEDOR

    public function crearProveedor(array $data): bool {

        $sql = "INSERT INTO proveedores (razon_social, telefono, email, cuit, cond_iva) VALUES (:razon_social, :telefono, :email, :cuit, :cond_iva)";

        $stmt = $this->db->prepare($sql);

        return $stmt->execute([
            ':razon_social' => $data['razon_social'],
            ':telefono' => $data['telefono'],
            ':email' => $data['email'],
            ':cuit' => $data['cuit'],
            ':cond_iva' => $data['cond_iva']
        ]);
    }

    // BUSCAR PROVEEDOR POR ID

    public function obtenerPorId(int $id): ?array {

        $sql = "SELECT id, razon_social, telefono, email, cuit, cond_iva FROM proveedores WHERE id = :id LIMIT 1";

        $stmt = $this->db->prepare($sql);

        $stmt->execute([':id' => $id]);

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

        return $proveedor ?: null;
    }

    // EDITAR PROVEEDOR

    public function actualizarProveedor(int $id, array $data): bool {
        
        if (empty($data)) {
            return false;
        }

        $campos = [];
        $params = [];

        foreach ($data as $campo => $valor) {
            $campos[] = "$campo = :$campo";
            $params[":$campo"] = $valor;
        }

        $params[':id'] = $id;

        $sql = "UPDATE proveedores SET " . implode(', ', $campos) . " WHERE id = :id";

        $stmt = $this->db->prepare($sql);

        return $stmt->execute($params);
    }

    // OBTENER ID DE PROVEEDOR CORRESPONDIENTE A UN ID DE PEDIDO

    public function obtenerIDProveedorPorPedido(int $idPedido): ?array {

        $sql = "SELECT p.id, p.razon_social, p.telefono, p.email FROM proveedores AS p
                    INNER JOIN pedidos AS pe ON (p.id = pe.id_proveedor)
                WHERE (pe.id = :id_pedido) LIMIT 1";

        $stmt = $this->db->prepare($sql);

        $stmt->execute([':id_pedido' => $idPedido]);

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    // VERIFICAR EXISTENCIA DE PROVEEDOR

    public function verificarExistencia(array $datosProveedor, ?int $idExcluir = null): bool {

        $sql = "SELECT 1 FROM proveedores WHERE (razon_social = :razon_social OR email = :email OR cuit = :cuit)";

        if ($idExcluir !== null) {
            $sql .= " AND id <> :id_excluir";
        }

        $sql .= " LIMIT 1";

        $stmt = $this->db->prepare($sql);

        $params = [
            ':razon_social' => $datosProveedor['razon_social'],
            ':email' => $datosProveedor['email'],
            ':cuit' => $datosProveedor['cuit']
        ];

        if ($idExcluir !== null) {
            $params[':id_excluir'] = $idExcluir;
        }

        $stmt->execute($params);

        return (bool) $stmt->fetchColumn();
    }
}