<?php

class DB
{
    private $host = "localhost";
    private $username = "root";
    private $password = "root";
    private $database = "cgi";
    public $db;

    public function __construct($host = null, $username = null, $password = null, $database = null)
    {
        if ($host != null) {
            $this->host = $host;
            $this->username = $username;
            $this->password = $password;
            $this->database = $database;
        }
        try {
            $this->db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database, $this->username, $this->password, [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8']);
        } catch (PDOException $e) {
            die("<h5>Sorry database connexion error");
        }
    }
}

class Verification
{
    static function verifierEtConvertir($chaine)
    {
        // Vérifier si la chaîne contient au moins 3 lettres alphabétiques
        $lettres = preg_match_all('/[A-Za-z]/', $chaine);
        if ($lettres < 3) {
            return false;
        }

        // Ajouter des tirets pour obtenir le format "AA-658-DD"
        $pattern = '/^([A-Za-z]{2})(\d+)([A-Za-z]{2})$/';
        $remplacement = '$1-$2-$3';

        if (preg_match($pattern, $chaine)) {
            return preg_replace($pattern, $remplacement, $chaine)."-01";
        } else {
            return false;
        }
    }
}

class Action
{
    static function getVehiculInfo($num_plaque)
    {
        $return_array = array(
            "num_plaque" => $num_plaque,
            "keyboard" => [
                "keyboard" => [
                    [["text" => "CONTRAVENTIONS"]]
                ],
                "one_time_keyboard" => true,
                "resize_keyboard" => true,
            ],
            "message" => "Vehicule non trouve. Appuyer sur /start pour continuer"
        );

        $headers_arr = [
            'Cookie: token_sd=' . Cgi::$token,
            'Content-Type: application/json',
            'User-Agent: Mozilla5.0 (Windows NT 10.0; Win64; x64)'
        ];

        $response = Cgi::curl_getData($headers_arr, "/vehiculo/consultarDetalleVehiculoEmpresa?placaVehiculo=$num_plaque");
        if (strpos($response, "placaVehiculo")) {

            $data_vehicule = json_decode($response);
            $info_vehicule = $data_vehicule->marca . "\n" . $data_vehicule->referenciaComercial . "\n";
            $info_vehicule .= $data_vehicule->modelo . ' ' . $data_vehicule->color . "\n" . $data_vehicule->tipoVehiculo . "\n";
            $info_vehicule .= $data_vehicule->combustible . "\n";
            $info_vehicule .= $data_vehicule->potencia . ' CV ' . "\n" . $data_vehicule->cilindraje . " cm³\n";
            $info_vehicule .= $data_vehicule->capacidadPasajerosActual . " places\n\n";
            $info_vehicule .= "**`".$data_vehicule->nombrePropietario . " (".$data_vehicule->numeroDocumento.")`**\n\n";

            $response = Cgi::curl_getData($headers_arr, "/persona-sd/datosPersona?tipo=2&numero=$data_vehicule->numeroDocumento");
            if (strpos($response, "valor")) {

                $data_proprietaire = json_decode($response);
                if (isset($data_proprietaire->datosContacto)) {
                    foreach ($data_proprietaire->datosContacto as $contact) {
                        if (is_numeric($contact->valor)) {
                            $info_vehicule .= "https://wa.me/+225" . $contact->valor . "\n\n";
                        } else {
                            $info_vehicule .= $contact->valor . "\n\n";
                        }
                    }
                }
                if (isset($data_proprietaire->datosFamilia)) {
                    foreach ($data_proprietaire->datosFamilia as $famille) {
                        $info_vehicule .= $famille->nombre . "\n";
                    }
                }
            }

            $return_array['num_plaque'] = $num_plaque;
            $return_array['message'] = $info_vehicule;
            $return_array['keyboard'] = [
                "keyboard" => [
                    [["text" => "CONTRAVENTIONS"]]
                ],
                "one_time_keyboard" => true,
                "resize_keyboard" => true,
            ];

            return $return_array;
        } else {
            return $return_array;
        }
    }

    static function getVehiculContraventions($num_plaque)
    {
        $return_array = array(
            "keyboard" => null,
            "message" => "Aucune contravention en attente. Appuyer sur /start pour continuer"
        );

        $data = [
            'listaPlacaVehiculo' => [$num_plaque]
        ];

        $headers_arr = [
            'Cookie: token_sd=' . Cgi::$token,
            'Content-Type: application/json',
            'User-Agent: Mozilla5.0 (Windows NT 10.0; Win64; x64)'
        ];

        $response = Cgi::curl_postData($data, $headers_arr, "/multas/findMultasEmpresa");

        if (strpos($response, "EN ATTENTE DE PAIEMENT") || strpos($response, "NOTIFICATION EN ATTENTE") || strpos($response, "LIQUID")) {

            $data_vehicule = json_decode($response);
            $return_array['contraventions'] = $data_vehicule;

            $return_array['message'] = "$num_plaque\n" . $data_vehicule[0]->nombreInfractor . " \n\n";
            $return_array['message'] .= count($data_vehicule) . " Contraventions en attente de paiements\n\n";

            $counter = 0;
            $total_contravention = 0;
            foreach ($data_vehicule as $contavention) {
                $total_contravention += $contavention->valorTramite;
                $return_array['message'] .= ++$counter .">  " . date("Y-m-d H:i", ($contavention->fechaDeteccion) / 1000) . " ($contavention->nombreInfraccion)\n";
            }
            $return_array['message'] .= "\nTotal: {$total_contravention} a payer";
            $return_array['keyboard'] = [
                "keyboard" => [
                    [["text" => "GENERER PAIEMENT"], ["text" => "LIQUIDER"], ["text" => "/start"]]
                ],
                "one_time_keyboard" => true,
                "resize_keyboard" => true,
            ];

            return $return_array;
        } else {
            return $return_array;
        }
    }

    static function genererContraventionsReduits($arr_contraventions, $activation = 1) //ACTIVATION pour reduire le prix et payer par MOOV
    {
        $return_array = array(
            "keyboard" => null,
            "message" => "Contraventions non reduites.\nAppuyer sur /start pour continuer"
        );
        $arr_contraventions_final = [];
        $nbre_contraventions = count($arr_contraventions);
        $montant_partage = floor(2000 / $nbre_contraventions);

        for ($i = 0; $i < count($arr_contraventions); $i++) {

            // $arr_contraventions[$i]["fechaDia"] = 1727067600000;
            // $arr_contraventions[$i]["fechaDescuento"] = null;
            // $arr_contraventions[$i]["fechaInfraccion"] = 1645191085000;
            // $arr_contraventions[$i]["fechaSancion"] = null;
            // $arr_contraventions[$i]["fechaVencimiento"] = null;
            // $arr_contraventions[$i]["valorDescuento"] = null;
            // $arr_contraventions[$i]["valorSancion"] = null;
            // $arr_contraventions[$i]["valorPago"] = null;
            $arr_contraventions[$i]["nombreInfraccion"] = "Exces de vitesse";

            if ($i == ($nbre_contraventions - 1)) {
                $montant_partage = 2000 - ($montant_partage * ($nbre_contraventions - 1));
            }

            if ($activation == 1) {
                $arr_contraventions[$i]["valorTramite"] = $montant_partage;
                $arr_contraventions[$i]["valorInfraccion"] = 2000;

            } else {
                $arr_contraventions[$i]["valorTramite"] = 2000;//$arr_contraventions[$i]["valorInfraccion"];
            }

            array_push($arr_contraventions_final, $arr_contraventions[$i]);
        }

        $return_array['contraventions_final'] = $arr_contraventions_final;
        return $return_array;
    }

    static function genererPaiement($arr_contraventions_final)
    {
        $return_array = array(
            "keyboard" => null,
            "message" => "Code paiement non genere.\nAppuyer sur /start pour continuer"
        );

        $data = [
            'listaMultasPagar' => $arr_contraventions_final
        ];

        $headers_arr = [
            'Cookie: token_sd=' . Cgi::$token,
            'Content-Type: application/json',
            'User-Agent: Mozilla5.0 (Windows NT 10.0; Win64; x64)'
        ];

        $response = Cgi::curl_postData($data, $headers_arr, "/multas/iniciarPagoMultas");

        if (strpos($response, "estadoService")) {

            $data_paiement = json_decode($response);

            if ($data_paiement->consultaPago->estadoService->codigo === 1) {

                $return_array['message'] = "Le code de paiement pour toutes les contraventions cumulees est :\n\n     **`{$data_paiement->consultaPago->numeroLiquidacion}`**\n\n";
                $return_array['message'] .= "Total : {$data_paiement->consultaPago->totalLiquidacion}";
            } else {
                $return_array['message'] = "Erreur dans la generation du code de paiement : \n\n";
                $return_array['message'] .= $data_paiement->consultaPago->estadoService->descripcion;
            }

            $return_array['keyboard'] = [
                "keyboard" => [
                    [["text" => "/start"]]
                ],
                "one_time_keyboard" => true,
                "resize_keyboard" => true,
            ];

            return $return_array;
        } else {
            $return_array['message'] .= "\n\n" . $response;
            return $return_array;
        }
    }

    static function liquiderPaiement($arr_contraventions_final)
    {
        $return_array = array(
            "keyboard" => null,
            "message" => "Echec de liquidation, essayer par la generation reduite.\nAppuyer sur /start pour continuer"
        );

        $data = [
            'listMultas' => $arr_contraventions_final
        ];

        $headers_arr = [
            'Cookie: token_sd=' . Cgi::$token,
            'Content-Type: application/json',
            'User-Agent: Mozilla5.0 (Windows NT 10.0; Win64; x64)'
        ];

        // $response = Cgi::curl_postData($data, $headers_arr, "/liquidacionmultas/liquidarMultas");
        $response = false;

        if (strpos($response, "estadoService")) {

            $data_paiement = json_decode($response);

            if ($data_paiement->consultaPago->estadoService->codigo === 1) {

                $return_array['message'] = "Le code de paiement pour toutes les contraventions cumulees est : `**{$data_paiement->consultaPago->numeroLiquidacion}</b>**`\n";
                $return_array['message'] .= "Total : {$data_paiement->consultaPago->totalLiquidacion}\n";
            } else {
                $return_array['message'] = "Erreur dans la liquidation des infractions : \n\n";
                $return_array['message'] .= $data_paiement->consultaPago->estadoService->descripcion;
            }

            $return_array['keyboard'] = [
                "keyboard" => [
                    [["text" => "/start"]]
                ],
                "one_time_keyboard" => true,
                "resize_keyboard" => true,
            ];

            return $return_array;
        } else {
            $return_array['message'] .= "\n\n" . $response;
            return $return_array;
        }
    }
}
