<?php
// declare(strict_types=1);
require_once("DataBase.php");
class Whats
{
    private $table;
    private $conn;

    public function __construct()
    {
        $main = new DataBase();
        $conn = $main->getConnection();

        $this->conn = $conn;
        $this->table = "whatsapp";
    }

    function validate() {}
    public function maxID(): int
    {
        $sql = "SELECT max(id) as maxID from {$this->table}";

        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
        $row = $stmt->fetch();

        return $row['maxID'] + 1;
    }

    public function contractMsg(int $contract_id): bool|array
    {
        $sql = "SELECT * from {$this->table} where contract_id = ?";

        $stmt = $this->conn->prepare($sql);
        $stmt->bindParam(1, $contract_id, PDO::PARAM_INT);
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            return $stmt->fetch();
        } else {
            return false;
        }
    }
    public function phoneMsg(int $phone): bool|array
    {
        $sql = "SELECT * from {$this->table} where phone = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bindParam(1, $phone, PDO::PARAM_INT);
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            return $stmt->fetch();
        } else {
            return false;
        }
    }
    public function branchMsg(int $branch): bool|array
    {
        $sql = "SELECT * from {$this->table} where branch = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bindParam(1, $branch, PDO::PARAM_INT);
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            return $stmt->fetch();
        } else {
            return false;
        }
    }

    public function insert(int $contract_id, int $invoice_id, $money_in): void
    {
        $contractData = $this->getContractData($contract_id);
        $cust_name = $contractData['cust_name'];
        $id = $this->maxID();
        $msg = "عميلنا العزيز \nالسادة :  $cust_name \n 
تم تأكيد استلام المبلغ  $money_in ريال سعودي   ،  بنجاح. \nمع تحياتنا،\n شركة الوسام لتأجير السيارات\n
Dear Customer,\nThe payment has been received successfully of SAR $money_in.\n
Best regards,\n Al Wisam Car Rental Company";
        // saudi phone
        if (str_starts_with($contractData['phone'], '0')) {
            $phone = substr($contractData['phone'], 1);
        }

        // Add country code 966
        $saudiPhone = "966" . $phone;
        $data = array(
            'id'           => $id,
            'phone'        => $saudiPhone,
            'msg'          => $msg,
            'contract_id'  => $contract_id,
            'invoice_id'   => $invoice_id,
            'branch'       => $contractData['branch']
        );
        $columns = implode(", ", array_keys($data));
        $placeholders = implode(", ", array_fill(0, count($data), "?"));

        $sql = "INSERT INTO {$this->table} ($columns)
                VALUES ($placeholders)";
        $stmt = $this->conn->prepare($sql);
        $i = 1;
        foreach ($data as $value) {
            $type = match (gettype($value)) {
                "boolean" => PDO::PARAM_BOOL,
                "integer" => PDO::PARAM_INT,
                "NULL" => PDO::PARAM_NULL,
                default => PDO::PARAM_STR
            };
            $stmt->bindValue($i++, $value, $type);
        }
        $stmt->execute();
    }
    //
    public function updateSent(int $id): bool
    {
        $sql = "UPDATE {$this->table} set sent = 2 WHERE id =?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bindParam(1, $id);
        return $stmt->execute();
    }

    function getContractData($contract_id): bool|array
    {
        $sql = $this->conn->prepare("SELECT customers.cust_name ,customers.phone ,branches.b_name as branch
from customers , contracts , branches
where contracts.cust_id = customers.cust_id
AND contracts.branch = branches.branchID
                    and contracts.contract_id = ?");
        $sql->bindParam(1, $contract_id);
        $sql->execute();
        if ($sql->rowCount() > 0) {
            $row = $sql->fetch(PDO::FETCH_ASSOC);
            return  $row;
        } else {
            return 0;
        }
    }

    function readyToSend()
    {
        $sql = "SELECT * FROM {$this->table} where sent < 2 ORDER BY id LIMIT 1";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            $row = $stmt->fetch();
            if ($row['sent_at'] !== null) {
                $start = strtotime($row['sent_at']);
                $date_today = date("Y-m-d H:i:s");
                $end = strtotime($date_today);
                $mano = $end - $start; // Time difference in seconds
            } else {
                $mano = 60; // for first run
            }
            if ($mano < 33) {
                return 0;
            } else {
                return $row;
            }
        } else {
            return 0;
        }
    }
    public function sendNextMessage(): void
    {
        //get data for sending
        $data = $this->readyToSend();
        if ($data != 0) {
            $curl = curl_init();

            // Prepare the data as an associative array
            $postData = array(
                "Function" => "result_link",
                "Phone"    => $data['phone'],//
                "Name"     => "الوسام المعتمد لتأجير السيارات",
                "LabId"    => "",
                "NetCode"  => "",
                "Text"     => $data['msg'],
                "Image"    => ""
            );

            // Convert the array to a proper JSON string
            $jsonData = json_encode($postData, JSON_UNESCAPED_UNICODE);

            // Check for JSON encoding errors
            if ($jsonData === false) {
                die('JSON encoding failed: ' . json_last_error_msg());
            }
// 'http://213.136.90.179:8748/message',
           curl_setopt_array($curl, array(
    CURLOPT_URL            => 'http://109.123.249.212:9999/message',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING       => '',
    CURLOPT_MAXREDIRS      => 10,
    CURLOPT_TIMEOUT        => 30, // Better to set a timeout (e.g. 30 seconds) instead of 0 (infinite)
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST  => 'POST',
    CURLOPT_POSTFIELDS     => $jsonData,
    CURLOPT_HTTPHEADER     => array(
        'Content-Type: application/json; charset=utf-8',
        'Content-Length: ' . strlen($jsonData)
    ),
));

            $response = curl_exec($curl);

            // Check for cURL errors
            if (curl_error($curl)) {
                echo 'Curl error: ' . curl_error($curl);
            } else {
                // Output the response
                $this->updateSent((int) $data['id']);
                echo $response;
            }

            curl_close($curl);
        }
    } //end auto sender
}