<?php
namespace Pemm\Controller;

use Pemm\Core\Controller as CoreController;
use Pemm\Model\Customer;
use Pemm\Model\Order;
use Pemm\Model\SmsProvider;
use Pemm\Model\User;
use Pemm\Model\CustomerVehicle;
use PDO;

class Sms
{
    private $container;
    private $language;
    private $customer;
    private $userId;

    // Yeni Vatansms API Bilgileri
    private const VATAN_API_ID   = 'c232f11c7f081b373cff7287';
    private const VATAN_API_KEY  = 'e461126470c5fdcca329c59f';
    private const SENDER         = 'V.Munoglu';

    public function __construct($check_user = true)
    {
        global $container;
        $this->container = $container;
        $this->language  = $container->get('language');

        if ($check_user === true) {
            if ((new Customer())->check()) {
                $this->customer = $this->container->get('customer');
                if (!empty($this->customer)) {
                    $this->userId = $this->container->get('customer')->getId();
                }
            }
        }
    }

    /**
     * Yeni Vatansms API ile SMS Gönderme (1toN)
     */
    private function SmsGonder($numara, $mesaj)
    {
        $params = [
            'api_id'               => self::VATAN_API_ID,
            'api_key'              => self::VATAN_API_KEY,
            'sender'               => self::SENDER,
            'message_type'         => 'normal',
            'message'              => $mesaj,
            'message_content_type' => 'bilgi',
            'phones'               => [$numara]
        ];

        $curl = curl_init();

        $curl_options = [
            CURLOPT_URL            => 'https://api.vatansms.net/api/v1/1toN',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_CUSTOMREQUEST  => 'POST',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_POSTFIELDS     => json_encode($params, JSON_UNESCAPED_UNICODE),
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'Accept: application/json'
            ]
        ];

        curl_setopt_array($curl, $curl_options);
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $curlError = curl_error($curl);
        curl_close($curl);

        // Hata kontrolü ve loglama
        if ($curlError) {
            error_log("Vatansms cURL Error: " . $curlError);
        }
        if ($httpCode !== 200) {
            error_log("Vatansms API Error - HTTP $httpCode: " . $response);
        }

        return $response;
    }

    /**
     * Ana SMS Gönderme Fonksiyonu
     */
    public function sendSms($number, $message, $isAdmin = false)
    {
        $smsProvider = (new SmsProvider())->find(1);
        if ($smsProvider->getStatus() !== '1') {
            return true;
        }

        // Admin'e gönderilecekse admin numarasını al
        if ($isAdmin) {
            $db = new PDO(
                "mysql:host=" . \Pemm\Config::DB_HOST . ";dbname=" . \Pemm\Config::DB_NAME,
                \Pemm\Config::DB_USER,
                \Pemm\Config::DB_PASSWORD
            );

            $stmt = $db->prepare("SELECT contact_number FROM user WHERE user_role = 1 LIMIT 1");
            $stmt->execute();
            $admin = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($admin && !empty($admin['contact_number'])) {
                $number = $admin['contact_number'];
            }
        }

        // Yeni API ile gönder
        $response = $this->SmsGonder($number, $message);

        return $response;
    }



    public function customerSendFile()
    {
        $user = (new Customer())->find($this->userId);
        $message_text = \Pemm\Core\Language::translate(
            strip_tags($user->getfirstName() . " " . $user->getlastName()) . ' uploaded a new file.'
        );
        $this->sendSms('', $message_text, true);
    }

    public function customerCreateSupport($wmvmessage)
    {
        $user = (new Customer())->find($this->userId);
        $message_text = \Pemm\Core\Language::translate(
            strip_tags($user->getfirstName() . " " . $user->getlastName()) .
            ' yeni bir destek talebi gönderdi. Mesaj: ' . $wmvmessage
        );
        $this->sendSms('', $message_text, true);
    }

    public function customerReplySupport($wmvmessage)
    {
        $user = (new Customer())->find($this->userId);
        $message_text = \Pemm\Core\Language::translate(
            strip_tags($user->getfirstName() . " " . $user->getlastName()) .
            ' yanıtlandı. Mesaj: ' . $wmvmessage
        );
        $this->sendSms('', $message_text, true);
    }

    public function registerSms($to_user)
    {
        $customer = (new Customer())->find($to_user);
        $message_text = \Pemm\Core\Language::translate(
            strip_tags($customer->getfirstName() . " " . $customer->getlastName()) . ', Aramıza Hoş Geldiniz.'
        );
        $this->sendSms($customer->getContactNumber(), $message_text);
    }

    public function orderSms($to_user)
    {
        $customer = (new Customer())->find($to_user);
        $order = (new Order())->findOneBy(['filter' => ['customer_id' => $to_user]]);

        $message_text = \Pemm\Core\Language::translate(
            $order->number . ' has been created. Order amount: ' .
            $order->totalCredit . ' ' . $order->currency .
            ' - Order status: ' . $this->language::translate($order->paymentStatus)
        );

        $this->sendSms($customer->getContactNumber(), $message_text);
    }

    public function adminChangeFileStatus($vdetail)
    {
        $customerVehicle = (new CustomerVehicle())->find($vdetail);
        if (!$customerVehicle) {
            throw new \Exception("CustomerVehicle bulunamadı.");
        }

        $customer = $customerVehicle->getCustomer();
        if (!$customer) {
            throw new \Exception("Customer bulunamadı.");
        }

        $validStatuses = ['awaiting payment', 'pending', 'process', 'completed', 'canceled'];
        $currentStatus = $customerVehicle->getStatus();

        $newStatus = $currentStatus;
        if (isset($_POST['status'])) {
            $newStatus = strtolower(str_replace('_', ' ', $_POST['status']));
            if ($newStatus === 'cancel') $newStatus = 'canceled';
            if (strpos($newStatus, 'awaiting') !== false && strpos($newStatus, 'payment') !== false) {
                $newStatus = 'awaiting payment';
            }
        }

        if ($newStatus === $currentStatus) {
            return;
        }

        $full_name = $customerVehicle->getWMVdata('wmv_vehicle_name') !== null
            ? $customerVehicle->getWMVdata('vehicle_full_name')
            : $customerVehicle->getVehicle()->getFullName();

        $message_text = \Pemm\Core\Language::translate(
            $full_name . ' aracınızın dosya durumu değişti. Yeni Dosya Durumu: '.
            $this->language::translate($newStatus)
        );

        $this->sendSms($customer->getContactNumber(), $message_text);

        $customerVehicle->setStatus($newStatus);
        $customerVehicle->store();

        error_log("Status changed from $currentStatus to $newStatus for vehicle ID: " . $customerVehicle->getId());
    }

    public function adminReplySupport($to_user, $wmvmessage)
    {
        $customer = (new Customer())->find($to_user);
        $message_text = \Pemm\Core\Language::translate(
            '"Destek talebiniz cevaplandı. Mesaj: ' . $wmvmessage
        );
        $this->sendSms($customer->getContactNumber(), $message_text);
    }

    public function testSms()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            try {
                $message_text = "Bu bir test SMS'idir. Gönderim zamanı: " . date('Y-m-d H:i:s');
                $response = $this->sendSms('', $message_text, true);

                echo json_encode([
                    'success' => true,
                    'message' => 'SMS başarıyla gönderildi.',
                    'response' => $response
                ]);
            } catch (\Exception $e) {
                http_response_code(500);
                echo json_encode([
                    'success' => false,
                    'message' => 'Hata oluştu: ' . $e->getMessage()
                ]);
            }
            exit;
        }

        include '../App/Views/test_sms.php';
    }
}