<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/whatsapp.php';
require_once __DIR__ . '/../vendor/autoload.php';

use Twilio\Rest\Client;

class NotificationController {

    private $conn;
    private $twilio;

    public function __construct() {
        $this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if ($this->conn->connect_error) {
            die("Error de conexión: " . $this->conn->connect_error);
        }
        $this->twilio = new Client(TWILIO_SID, TWILIO_TOKEN);
    }

    public function sendWhatsAppNotification($customerId, $message) {
        $stmt = $this->conn->prepare("SELECT phone FROM customers WHERE id = ?");
        $stmt->bind_param("i", $customerId);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $phone = $result->fetch_assoc()['phone'];
            try {
                $this->twilio->messages->create(
                    "whatsapp:" . $phone,
                    [
                        'from' => "whatsapp:" . TWILIO_WHATSAPP_FROM,
                        'body' => $message
                    ]
                );
                $this->logNotification($customerId, $message, 'enviado');
                return true;
            } catch (\Twilio\Exceptions\TwilioException $e) {
                $this->logNotification($customerId, $message, 'fallido');
                return false;
            }
        }
        return false;
    }

    private function logNotification($customerId, $message, $status) {
        $stmt = $this->conn->prepare("INSERT INTO notifications_log (customer_id, message, status) VALUES (?, ?, ?)");
        $stmt->bind_param("iss", $customerId, $message, $status);
        $stmt->execute();
    }
}
?>