<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

class CheckoutController extends Controller
{
    public function index()
    {
        $cart = $_SESSION['cart'] ?? [];
        if (empty($cart)) {
            $this->redirect('/carrinho');
        }

        $savedCustomer = null;
        if (!empty($_COOKIE['osc_customer'])) {
            $decoded = json_decode($_COOKIE['osc_customer'], true);
            if (is_array($decoded) && !empty($decoded['updated_at'])) {
                if ($decoded['updated_at'] > (time() - 2 * 24 * 60 * 60)) {
                    $savedCustomer = $decoded;
                }
            }
        }

        $subtotal = 0;
        foreach ($cart as $item) {
            $subtotal += $item['total_price'];
        }
        $prefs = $_SESSION['checkout_prefs'] ?? [
            'mode' => 'delivery',
            'name' => '',
            'phone' => '',
            'address' => '',
            'neighborhood' => '',
            'delivery_fee' => 0,
        ];

        if ($savedCustomer) {
            if (empty($prefs['name'])) {
                $prefs['name'] = $savedCustomer['name'] ?? '';
            }
            if (empty($prefs['phone'])) {
                $prefs['phone'] = $savedCustomer['phone'] ?? '';
            }
            if (empty($prefs['address'])) {
                $prefs['address'] = $savedCustomer['address'] ?? '';
            }
            if (empty($prefs['neighborhood'])) {
                $prefs['neighborhood'] = $savedCustomer['neighborhood'] ?? '';
            }
        }

        $db = Database::getInstance()->getConnection();
        $deliveryZones = $db->query("SELECT * FROM delivery_zones WHERE active = 1 ORDER BY neighborhood ASC")->fetchAll();

        $deliveryFee = $prefs['delivery_fee'] ?? 0;
        $total = $subtotal + $deliveryFee;
        $this->view('client.checkout', [
            'cart' => $cart,
            'subtotal' => $subtotal,
            'deliveryFee' => $deliveryFee,
            'total' => $total,
            'prefs' => $prefs,
            'savedCustomer' => $savedCustomer,
            'deliveryZones' => $deliveryZones,
        ]);
    }

    public function process()
    {
        $cart = $_SESSION['cart'] ?? [];
        if (empty($cart)) {
            $this->redirect('/');
        }

        $prefs = $_SESSION['checkout_prefs'] ?? [];

        $mode = $_POST['mode'] ?? 'delivery';
        $name = $_POST['name'] ?? ($prefs['name'] ?? '');
        $phone = $_POST['phone'] ?? ($prefs['phone'] ?? '');
        $address = $_POST['address'] ?? '';
        $neighborhood = $_POST['neighborhood'] ?? ($prefs['neighborhood'] ?? '');
        $payment = $_POST['payment'];
        
        $total = 0;
        foreach ($cart as $item) {
            $total += $item['total_price'];
        }

        // Recalcular delivery fee baseado no bairro para segurança
        $deliveryFee = 0;
        $db = Database::getInstance()->getConnection();
        
        // Se modo entrega e tem bairro, calcula taxa.
        if ($mode === 'delivery' && !empty($neighborhood)) {
            $stmt = $db->prepare("SELECT fee FROM delivery_zones WHERE neighborhood = ? AND active = 1");
            $stmt->execute([$neighborhood]);
            $zone = $stmt->fetch();
            if ($zone) {
                $deliveryFee = (float) $zone['fee'];
            }
        } else {
            // Se retirada, zera taxa e limpa endereço
            $deliveryFee = 0;
            if ($mode === 'pickup') {
                $address = ''; // Não salva endereço se for retirada
            }
        }

        $total += $deliveryFee;
        
        try {
            $db->beginTransaction();

            // Criar Pedido
            $stmt = $db->prepare("INSERT INTO orders (customer_name, customer_phone, customer_address, total_amount, payment_method, status, delivery_fee) VALUES (?, ?, ?, ?, ?, 'pending', ?)");
            $stmt->execute([$name, $phone, $address . ($neighborhood ? " - $neighborhood" : ""), $total, $payment, $deliveryFee]);
            $orderId = $db->lastInsertId();

            // Itens do Pedido
            $stmtItem = $db->prepare("INSERT INTO order_items (order_id, product_name, quantity, unit_price, total_price, notes) VALUES (?, ?, ?, ?, ?, ?)");

            // Baixa de Estoque (Backoffice Automático)
            $stmtStock = $db->prepare("UPDATE ingredients i JOIN product_ingredients pi ON i.id = pi.ingredient_id SET i.stock_quantity = i.stock_quantity - (pi.quantity * ?) WHERE pi.product_id = ?");

            foreach ($cart as $item) {
                $stmtItem->execute([$orderId, $item['name'], $item['quantity'], $item['price'], $item['total_price'], $item['notes']]);
                
                // Reduzir estoque
                $stmtStock->execute([$item['quantity'], $item['product_id']]);
            }

            $db->commit();

            $customerData = [
                    'name' => $name,
                    'phone' => $phone,
                    'address' => $address,
                    'neighborhood' => $neighborhood,
                    'mode' => $mode,
                    'updated_at' => time(),
                ];
            setcookie('osc_customer', json_encode($customerData), time() + 2 * 24 * 60 * 60, '/');
            
            // Limpar carrinho
            unset($_SESSION['cart']);
            unset($_SESSION['checkout_prefs']);

            // Redirecionar para sucesso
            $this->redirect("/pedido/sucesso/$orderId");

        } catch (\Exception $e) {
            $db->rollBack();
            die("Erro ao processar pedido: " . $e->getMessage());
        }
    }

    public function savePreferences()
    {
        $mode = $_POST['mode'] ?? 'delivery';
        $name = trim($_POST['name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $address = '';
        $neighborhood = '';
        $deliveryFee = 0;

        if ($mode === 'delivery') {
            $address = trim($_POST['address'] ?? '');
            $neighborhood = trim($_POST['neighborhood'] ?? '');
            
            // Get fee from DB
            $db = Database::getInstance()->getConnection();
            $stmt = $db->prepare("SELECT fee FROM delivery_zones WHERE neighborhood = ? AND active = 1");
            $stmt->execute([$neighborhood]);
            $zone = $stmt->fetch();
            if ($zone) {
                $deliveryFee = (float) $zone['fee'];
            }
        } else {
            $name = trim($_POST['pickup_name'] ?? $name);
            $phone = trim($_POST['pickup_phone'] ?? $phone);
            $deliveryFee = 0;
        }

        $_SESSION['checkout_prefs'] = [
            'mode' => $mode,
            'name' => $name,
            'phone' => $phone,
            'address' => $address,
            'neighborhood' => $neighborhood,
            'delivery_fee' => $deliveryFee,
        ];

        $this->json(['success' => true, 'fee' => $deliveryFee]);
    }

    public function success($orderId)
    {
        // Aqui geraria o link do WhatsApp
        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("SELECT * FROM orders WHERE id = ?");
        $stmt->execute([$orderId]);
        $order = $stmt->fetch();

        if (!$order) {
            $this->redirect('/');
        }

        $pixConfig = null;
        // Verifica se é Pix (supondo que o value do radio button seja 'pix')
        // Ajustar para comparar com string correta se necessário
        if (stripos($order['payment_method'], 'pix') !== false) {
            $stmtPix = $db->query("SELECT * FROM payment_settings WHERE method = 'pix' AND is_active = 1");
            $pixConfig = $stmtPix->fetch();
        }

        // Mensagem WhatsApp
        $msg = "Olá, sou *{$order['customer_name']}*! Acabei de fazer o pedido #{$orderId} no OSiriCascudo. Total: R$ " . number_format($order['total_amount'], 2, ',', '.');
        $whatsappLink = "https://wa.me/55999999999?text=" . urlencode($msg);

        $this->view('client.success', [
            'order' => $order, 
            'whatsappLink' => $whatsappLink,
            'pixConfig' => $pixConfig
        ]);
    }
}
