<?php

namespace Core\App\Services;

use Core\App\Support\OrderPricing;

use Core\App\Models\OrderModel;
use Core\App\Models\Settings;
use Core\App\Models\ProductModel;
use Core\App\Models\SecurityLog;

/**
 * Google Sheets Exporter (Service Account)
 * - Queues confirmed orders as JSON files
 * - Cron task sends them to Google Sheets
 */
class GoogleSheetsExporter
{
    private Settings $settings;
    private OrderModel $orders;
    private ProductModel $products;

    public function __construct()
    {
        $this->settings = new Settings();
        $this->orders   = new OrderModel();
        $this->products = new ProductModel();
    }


    /**
     * Build Algeria-focused row payload.
     */
    private function buildRowPayload(array $order): ?array
    {
        $extra = $order['extra'] ?? [];

        $productTitle = '';
        try {
            $product = $this->products->getById((int)($order['product_id'] ?? 0));
            if ($product && !empty($product['title'])) {
                $productTitle = (string)$product['title'];
            }
        } catch (\Throwable $e) {
            $productTitle = '';
        }

        // Fallback to snapshot stored in extra
        if ($productTitle === '' && !empty($extra['product']['name'])) {
            $productTitle = (string)$extra['product']['name'];
        }

        $qty = (int)($extra['quantity'] ?? 1);
        if ($qty < 1) {
            $qty = 1;
        }

        $size  = $extra['variants']['size']  ?? '';
        $color = $extra['variants']['color'] ?? '';

        $wilaya  = $extra['shipping']['destination']['state_code'] ?? ($order['state_code'] ?? '');
        $commune = $extra['shipping']['destination']['city_name']  ?? ($order['city_name'] ?? '');

        $shippingType  = $extra['shipping']['type'] ?? '';
        $shippingPrice = $extra['pricing']['shipping_price'] ?? null;
        if ($shippingPrice === null) {
            $shippingPrice = $extra['shipping_price'] ?? null;
        }

        $total = OrderPricing::effectiveTotal($order);

        $source = $extra['meta']['source'] ?? '';
        $whatsappClick = $extra['meta']['whatsapp_click'] ?? '';
        $shippingCompany = $extra['shipping']['provider'] ?? '';

        return [
            'order_id'        => (int)($order['id'] ?? 0),
            'date'            => (string)($order['created_at'] ?? date('Y-m-d H:i:s')),
            'product_title'   => $productTitle,
            'quantity'        => $qty,
            'variant_size'    => (string)$size,
            'variant_color'   => (string)$color,
            'full_name'       => (string)($order['full_name'] ?? ''),
            'phone'           => (string)($order['phone'] ?? ''),
            'wilaya'          => (string)$wilaya,
            'commune'         => (string)$commune,
            'shipping_type'   => (string)$shippingType,
            'shipping_price'  => (float)($shippingPrice ?? 0),
            'total'           => (float)($total ?? 0),
            'status'          => (string)($order['order_status'] ?? ''),
            'notes'           => (string)($extra['notes'] ?? ''),
            'source'          => (string)$source,
            'whatsapp_click'  => (string)$whatsappClick,
            'shipping_company'=> (string)$shippingCompany,
        ];
    }

    /**
     * استخدام OAuth بدلاً من Service Account إذا كان مُفعّلاً
     */
    public function queueConfirmedOrder(int $orderId): bool
    {
        // تحقق من تفعيل OAuth أولاً
        $stmt = \db()->prepare("SELECT setting_value FROM settings WHERE setting_key = 'gsheets_oauth_enabled' LIMIT 1");
        $stmt->execute();
        $oauthEnabled = $stmt->fetchColumn();

        if ($oauthEnabled == '1') {
            return $this->queueViaOAuth($orderId);
        }

        // fallback للـ Service Account القديم
        return $this->queueViaServiceAccount($orderId);
    }

    private function queueViaOAuth(int $orderId): bool
    {
        $order = $this->orders->getById($orderId);
        if (!$order) {
            return false;
        }

        // Respect export mode: confirmed_only (default) OR all_orders
        $exportMode = \Core\App\Models\Settings::getStatic('gsheets_export_mode', 'confirmed_only');
        if ($exportMode === 'confirmed_only' && ($order['order_status'] ?? '') !== 'confirmed') {
            return false;
        }

        $payload = $this->buildRowPayload($order);
        if (!$payload) return false;

        // merge_variants support
        $mergeVariants = \db()->query("SELECT setting_value FROM settings WHERE setting_key='gsheets_oauth_merge_variants' LIMIT 1")->fetchColumn();
        if ($mergeVariants == '1') {
            $product = $payload['product_title'];
            if (!empty($payload['variant_size']))  $product .= ' - ' . $payload['variant_size'];
            if (!empty($payload['variant_color'])) $product .= ' - ' . $payload['variant_color'];
            $payload['product_title']  = $product;
            $payload['variant_size']   = '';
            $payload['variant_color']  = '';
        }

        $dir  = ROOT_PATH . '/storage/queue/gsheets/pending';
        if (!is_dir($dir)) @mkdir($dir, 0777, true);

        $file = $dir . '/oauth_order_' . $orderId . '.json';
        $job  = [
            'mode'       => 'oauth',
            'order_id'   => $orderId,
            'attempts'   => 0,
            'created_at' => date('Y-m-d H:i:s'),
            'row'        => $payload,
        ];

        return @file_put_contents($file, json_encode($job, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) !== false;
    }

    private function queueViaServiceAccount(int $orderId): bool
    {
        if ((int)$this->settings->get('gsheets_enabled', 0) !== 1) return false;

        $order = $this->orders->getById($orderId);
        if (!$order || ($order['order_status'] ?? '') !== 'confirmed') return false;

        $payload = $this->buildRowPayload($order);
        if (!$payload) return false;

        $dir  = ROOT_PATH . '/storage/queue/gsheets/pending';
        if (!is_dir($dir)) @mkdir($dir, 0777, true);

        $file = $dir . '/order_' . $orderId . '.json';
        $job  = [
            'order_id'   => $orderId,
            'attempts'   => 0,
            'created_at' => date('Y-m-d H:i:s'),
            'row'        => $payload,
        ];

        return @file_put_contents($file, json_encode($job, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) !== false;
    }
}