<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/CustomerController.php';

class SaleController {

    private $conn;
    private $customerController;

    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->customerController = new CustomerController();
    }

    public function createSale($cart, $customer_phone, $referral_code, $payment_method) {
        $total = 0;
        foreach ($cart as $item) {
            $total += $item['price'];
        }

        $stmt = $this->conn->prepare("INSERT INTO sales (total, payment_method) VALUES (?, ?)");
        $stmt->bind_param("ds", $total, $payment_method);
        
        if ($stmt->execute()) {
            $sale_id = $stmt->insert_id;
            $this->saveSaleItems($sale_id, $cart);
            // Actualizar el stock
            $this->updateStock($cart);

            // Asignar puntos si hay un cliente
            if (!empty($customer_phone)) {
                $customerId = $this->customerController->findOrCreateCustomer($customer_phone);
                $this->conn->query("UPDATE customers SET last_purchase_date = CURDATE() WHERE id = $customerId");
                $points = floor($total / 10);
                if ($points > 0) {
                    $this->customerController->addPoints($customerId, $points, 'Compra');
                }

                // Aplicar referido
                if (!empty($referral_code)) {
                    $this->applyReferral($referral_code, $customerId, $sale_id);
                }
            }

            echo json_encode(['success' => true, 'message' => 'Venta registrada con éxito.']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Error al registrar la venta.']);
        }
    }

    private function applyReferral($referral_code, $referred_id, $sale_id) {
        $stmt = $this->conn->prepare("SELECT id FROM customers WHERE referral_code = ?");
        $stmt->bind_param("s", $referral_code);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $referrer_id = $result->fetch_assoc()['id'];
            // Dar punto extra al referidor
            $this->customerController->addPoints($referrer_id, 1, "Referido #$referred_id");
            // Registrar el referido
            $stmt = $this->conn->prepare("INSERT INTO referrals (referrer_id, referred_id) VALUES (?, ?)");
            $stmt->bind_param("ii", $referrer_id, $referred_id);
            $stmt->execute();
            // Añadir nota sobre el topping gratis
            $this->conn->query("UPDATE sales SET notes = 'Topping gratis por referido' WHERE id = $sale_id");
            // Notificar al referidor
            $notificationController = new NotificationController();
            $notificationController->sendWhatsAppNotification($referrer_id, "¡Gracias por referir a un amigo! Has ganado 1 punto.");
        }
    }

    private function createReferralNotificationTask($referrer_id, $referred_id) {
        $description = "Notificar al cliente #$referrer_id sobre el referido exitoso del cliente #$referred_id.";
        $stmt = $this->conn->prepare("INSERT INTO tasks (description) VALUES (?)");
        $stmt->bind_param("s", $description);
        $stmt->execute();
    }

    private function updateStock($cart) {
        $product_counts = [];
        foreach ($cart as $item) {
            if (!isset($product_counts[$item['name']])) {
                $product_counts[$item['name']] = 0;
            }
            $product_counts[$item['name']]++;
        }

        foreach ($product_counts as $name => $count) {
            $this->conn->query("UPDATE products SET stock = stock - $count WHERE name = '$name'");
        }
    }

    private function saveSaleItems($sale_id, $cart) {
        $product_counts = [];
        foreach ($cart as $item) {
            if (!isset($product_counts[$item['name']])) {
                $product_counts[$item['name']] = ['id' => $this->getProductIdByName($item['name']), 'quantity' => 0];
            }
            $product_counts[$item['name']]['quantity']++;
        }

        foreach ($product_counts as $name => $data) {
            $stmt = $this->conn->prepare("INSERT INTO sale_items (sale_id, product_id, quantity) VALUES (?, ?, ?)");
            $stmt->bind_param("iii", $sale_id, $data['id'], $data['quantity']);
            $stmt->execute();
        }
    }

    private function getProductIdByName($name) {
        $stmt = $this->conn->prepare("SELECT id FROM products WHERE name = ?");
        $stmt->bind_param("s", $name);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc()['id'];
    }

    public function getTodaySales() {
        $result = $this->conn->query("SELECT * FROM sales WHERE DATE(created_at) = CURDATE()");
        $sales = [];
        while ($row = $result->fetch_assoc()) {
            $sales[] = $row;
        }
        return $sales;
    }

    public function getSalesBySeller() {
        $result = $this->conn->query("SELECT u.username, COUNT(s.id) as sale_count, SUM(s.total) as total_sales FROM sales s JOIN users u ON s.user_id = u.id GROUP BY u.username");
        $sales = [];
        while ($row = $result->fetch_assoc()) {
            $sales[] = $row;
        }
        return $sales;
    }

    public function getSalesByMonth() {
        $result = $this->conn->query("SELECT DATE_FORMAT(created_at, '%Y-%m') as month, SUM(total) as total_sales FROM sales GROUP BY month");
        $sales = [];
        while ($row = $result->fetch_assoc()) {
            $sales[] = $row;
        }
        return $sales;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    if (isset($data['action']) && $data['action'] === 'create_sale') {
        session_start();
        $saleController = new SaleController();
        $saleController->createSale($data['cart'], $data['customer_phone'], $data['referral_code'], $data['payment_method'], $_SESSION['user_id']);
    }
}
?>