<?php

namespace Pemm\Controller; 
use Pemm\Core\Controller as CoreController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Pemm\Model\Customer;
use Pemm\Model\Order;
use Symfony\Component\HttpFoundation\JsonResponse;
use Twilio\Rest\Client;
use Pemm\Model\SmsProvider;
use Pemm\Model\User;
use Pemm\Model\CustomerVehicle;
use PDO;


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

    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();
                }
            }
        }
    }

    /**
     * Send Sms Main Function
     *
     * @param $number
     * @param $message
     * @param bool $isAdmin
     * @return void
     * @throws \Twilio\Exceptions\ConfigurationException
     * @throws \Twilio\Exceptions\TwilioException
     */
    public function sendSms($number, $message, $isAdmin = false){
        $smsProvider = (new SmsProvider())->find(1);

        if ($smsProvider->getStatus() !== '1') {
            return TRUE;
        }

        $account_sid = $smsProvider->getToken();
        $auth_token = $smsProvider->getToken2();
        $twilio_number = '+'.$smsProvider->getNumber();

        $client = new Client($account_sid, $auth_token);

        if ($isAdmin) {
            // Admin numarasını veritabanından al
            $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) {
                $number = $admin['contact_number'];
            }
        }

        $message = $client->messages->create(
            $number,
            array(
                'from' => $twilio_number,
                'body' => $message
            )
        );

        return $message;
    }

    /**
     * Customer Send File sms to Admin
     *
     * @return void
     * @throws \Twilio\Exceptions\ConfigurationException
     * @throws \Twilio\Exceptions\TwilioException
     */
    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); // Admin'e gönderiliyor
    }

    /**
     * Customer Create Support sms to Admin
     *
     * @return void
     * @throws \Twilio\Exceptions\ConfigurationException
     * @throws \Twilio\Exceptions\TwilioException
     */
    public function customerCreateSupport($wmvmessage){
        $user = (new Customer())->find($this->userId);
        $message_text = \Pemm\Core\Language::translate(strip_tags($user->getfirstName()." ".$user->getlastName()).' sent a new support request. Message: ' . $wmvmessage);
        $this->sendSms('', $message_text, true); // Admin'e gönderiliyor
    }

    /**
     * Customer Reply Current Support sms to Admin
     *
     * @return void
     * @throws \Twilio\Exceptions\ConfigurationException
     * @throws \Twilio\Exceptions\TwilioException
     */
    public function customerReplySupport($wmvmessage){
        $user = (new Customer())->find($this->userId);
        $message_text = \Pemm\Core\Language::translate(strip_tags($user->getfirstName()." ".$user->getlastName()).' replied. Message: ' . $wmvmessage);
        $this->sendSms('', $message_text, true); // Admin'e gönderiliyor
    }


    /**
     * Register Sms
     * @param $to_user
     * @return void
     */
    public function registerSms($to_user){

        $customer = (new Customer())->find($to_user);

        $message_text = \Pemm\Core\Language::translate(strip_tags($customer->getfirstName()." ".$customer->getlastName()).', Welcome to Join Us.');

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

    /**
     * Success Order Sms
     *
     * @param $to_user
     * @return void
     * @throws \Twilio\Exceptions\ConfigurationException
     * @throws \Twilio\Exceptions\TwilioException
     */
    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);
    }


    /**
     * Admin Change File Status sms to Customer
     *
     * @param int $vdetail CustomerVehicle ID
     * @param string $newStatus Yeni statü
     * @return void
     * @throws \Twilio\Exceptions\ConfigurationException
     * @throws \Twilio\Exceptions\TwilioException
     */
    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ı.");
        }
    
        // Geçerli statü değerleri (sıralı)
        $validStatuses = ['awaiting payment', 'pending', 'process', 'completed', 'canceled'];
    
        // Mevcut statüyü al
        $currentStatus = $customerVehicle->getStatus();

        // Statü değişikliği için POST verilerini kontrol et
        if (isset($_POST['status'])) {
            $newStatus = strtolower(str_replace('_', ' ', $_POST['status'])); // Küçük harfe çevir ve alt çizgileri boşluklarla değiştir
        
            // 'cancel' durumunu 'canceled' olarak düzelt
            if ($newStatus === 'cancel') {
                $newStatus = 'canceled';
            }
            
            // 'awaiting payment' durumu için özel kontrol
            if (strpos($newStatus, 'awaiting') !== false && strpos($newStatus, 'payment') !== false) {
                $newStatus = 'awaiting payment';
            }
            
            if (!in_array($newStatus, $validStatuses)) {
                throw new \Exception("Geçersiz statü değeri: " . $newStatus);
            }
        } else {
            $newStatus = $currentStatus;
        }

        // Eğer statü değişmediyse, işlem yapma
        if ($newStatus === $currentStatus) {
            return;
        }

        // Yeni status ile SMS mesajını oluştur
        $full_name = $customerVehicle->getWMVdata('wmv_vehicle_name') != NULL 
            ? $customerVehicle->getWMVdata('vehicle_full_name') 
            : $customerVehicle->getVehicle()->getFullName();
        
        $message_text = \Pemm\Core\Language::translate('The file status of your ' . $full_name . ' Vehicle has changed. New File Status: ' . $this->language::translate($newStatus));

        // SMS'i gönder
        $this->sendSms($customer->getContactNumber(), $message_text);

        // CustomerVehicle'ın statüsünü güncelle
        $customerVehicle->setStatus($newStatus);
        $customerVehicle->store(); // Veritabanında güncelle

        // Hata ayıklama için log
        error_log("Status changed from $currentStatus to $newStatus for vehicle ID: " . $customerVehicle->getId());
    }
    /**
     * Admin Reply Support sms to Customer
     *
     * @param $to_user
     * @return void
     * @throws \Twilio\Exceptions\ConfigurationException
     * @throws \Twilio\Exceptions\TwilioException
     */
    public function adminReplySupport($to_user, $wmvmessage){

        $customer = (new Customer())->find($to_user);
		
         $message_text = \Pemm\Core\Language::translate('Your Support Request Has Been Answered. Message: ' . $wmvmessage);

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


   
    public function testSms()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            try {
                ini_set('display_errors', 1);
                ini_set('display_startup_errors', 1);
                error_reporting(E_ALL);

                $message_text = "Bu bir test SMS'idir. Gönderim zamanı: " . date('Y-m-d H:i:s');
                $message = $this->sendSms('', $message_text, true); // Admin'e test SMS'i gönder

                echo json_encode([
                    'success' => true,
                    'message' => 'SMS başarıyla gönderildi.',
                    'adminNumber' => $message->to,
                    'smsStatus' => $message->status,
                    'smsId' => $message->sid
                ]);

            } catch (\Exception $e) {
                http_response_code(500);
                echo json_encode([
                    'success' => false,
                    'message' => 'Hata oluştu: ' . $e->getMessage(),
                    'trace' => $e->getTraceAsString()
                ]);
            }
            exit;
        }

        // HTML sayfasını göster
        include '../App/Views/test_sms.php';
    }
}
