<?php

//TimeLe$$ Classics

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\VdbInventoryLog;
use Illuminate\Support\Facades\Http;
use App\Models\SamayajewelryDiamond;
use App\Models\BtDiamond;
use Illuminate\Support\Facades\DB;
use Log;
use Illuminate\Support\Facades\Mail;

class ProductImportController extends Controller
{
    /**
     * Color mapping: Diamond color codes → filename color names
     * Maps API color codes to the color names used in your image filenames
     * 
     * Your folder structure: /public/assets/color/
     * Filename pattern: {shape}-{color}.jpg
     * Example: round-yellow.jpg, cushion-blue.jpg, heart-pink.jpg
     */
    private function getColorNameMap()
    {
        return [
            // White diamonds (Natural diamonds)
            'D'  => 'white',
            'E'  => 'white',
            'F'  => 'white',
            'G'  => 'white',
            'H'  => 'white',
            'I'  => 'white',
            'J'  => 'white',
            'H-I' => 'white',

            // White Face Up diamonds
            'K'  => 'white',
            'L'  => 'white',
            'M'  => 'white',

            // Yellow diamonds
            'Q-R' => 'yellow',
            'S-T' => 'yellow',
            'U-V' => 'yellow',
            'W-X' => 'yellow',
            'Y-Z' => 'yellow',
            'YELLOW' => 'yellow',

            // Fancy colors - EXACTLY as they appear in your filenames
            'BLACK' => 'black',
            'BLUE'  => 'blue',
            'PINK'  => 'pink',
            'PURPLE' => 'purple',
            'BROWN' => 'brown',
            'CHAMPAGNE' => 'champagne',
            'ORANGE' => 'orange',
            'GREEN' => 'green',
            'FANCY VIVID BLUISH GREEN' => 'green',
            'FANCY VIVID GREEN' => 'green',

            // Fallback
            'OTHER' => null,
        ];
    }

    /**
     * Shape codes → filename shape names (lowercase)
     * Your images are named like: round-yellow.jpg, cushion-blue.jpg
     */
    private function getShapeToFilenameMap()
    {
        return [
            'ROUND'     => 'round',
            'RD'        => 'round',
            'RBC'       => 'round',
            'PRINCESS'  => 'princess',
            'PR'        => 'princess',
            'PS'        => 'princess',
            'CUSHION'   => 'cushion',
            'CU'        => 'cushion',
            'CUSH'      => 'cushion',
            'EMERALD'   => 'emerald',
            'EM'        => 'emerald',
            'OVAL'      => 'oval',
            'OV'        => 'oval',
            'RADIANT'   => 'radiant',
            'RAD'       => 'radiant',
            'RA'        => 'radiant',
            'ASSCHER'   => 'asscher',
            'AS'        => 'asscher',
            'AC'        => 'asscher',
            'MARQUISE'  => 'marquise',
            'MQ'        => 'marquise',
            'MAR'       => 'marquise',
            'HEART'     => 'heart',
            'HT'        => 'heart',
            'HE'        => 'heart',
            'PEAR'      => 'pear',
            'PE'        => 'pear',
            'PSH'       => 'pear',
        ];
    }

    private function getToken()
    {
        $response = Http::asForm()->post(
            "https://brainapis.com/api/bt/get-token",
            [
                'username' => 'brillianttouch',
                'password' => 'brillianttouch!123!'
            ]
        );

        return $response->json()['token'] ?? null;
    }

    private function getDiamondData($token)
    {
        $response = Http::withToken($token)
            ->get("https://brainapis.com/api/bt/diamond");

        $records = $response->json()['record'] ?? [];

        // ===== FILTER: Only return Lab Grown diamonds =====
        return array_filter($records, function ($record) {
            $diamondType = strtolower(trim((string) ($record['DIA'] ?? '')));
            return $diamondType === 'lab grown';
        });
    }

    private function str($val)
    {
        $val = trim($val ?? '');
        return ($val === '' || strtolower($val) === 'null' || $val === '?')
            ? null
            : $val;
    }

    private function num($val)
    {
        return is_numeric($val) ? (float)$val : 0;
    }

    private function isValidImage($url)
    {
        if (empty($url)) {
            return false;
        }

        try {
            $headers = @get_headers($url);
            if (!$headers || strpos($headers[0], '200') === false) {
                return false;
            }

            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    private function isValidImage1($url)
    {
        if (empty($url)) return false;

        try {
            $headers = @get_headers($url);
            return ($headers && strpos($headers[0], '200') !== false);
        } catch (\Exception $e) {
            return false;
        }
    }

    private function cleanString($value)
    {
        $value = trim($value ?? '');

        return ($value === '' || strtolower($value) === 'null' || $value === '?')
            ? null
            : $value;
    }

    private function decimalOrNull($value)
    {
        $value = trim($value ?? '');

        return is_numeric($value) ? $value : null;
    }

    private function cleanValue($value)
    {
        $value = trim($value ?? '');
        return ($value === '') ? null : $value;
    }

    private function cleanDecimal($value)
    {
        return ($value === '' || $value === null) ? null : (float) $value;
    }

    private function finalPrice($weight = 1, $buy_price = 0)
    {
        return ($buy_price * 1) + $buy_price;
    }

    private function amount($weight = 1, $buy_price = 0)
    {
        return $buy_price * $weight;
    }

    private function getShapeMasterIdFromVariant($shapeSeq, $shapeMap)
    {
        $shapeSeq = strtoupper(trim((string) $shapeSeq));
        if ($shapeSeq === '') {
            \Log::warning('shape_master_id: SHAPE_SEQ was empty/missing on this row');
            return null;
        }

        foreach ($shapeMap as $shape) {
            $variants = array_map('trim', explode(',', strtoupper($shape->shape_family ?? '')));

            if (in_array($shapeSeq, $variants)) {
                return $shape->id;
            }
        }

        \Log::warning('shape_master_id: no match found for SHAPE_SEQ', ['shape_seq' => $shapeSeq]);

        return null;
    }

    private function mapDiamond($row, $stock_id, $vendor_id, $shapeMap)
    {
        // ===== SAFETY CHECK: Skip if not Lab Grown =====
        $diamondType = strtolower(trim((string) ($row['DIA'] ?? '')));
        if ($diamondType !== 'lab grown') {
            \Log::warning('mapDiamond: Skipping non-Lab Grown diamond', ['packet_no' => $stock_id, 'type' => $row['DIA']]);
            return null;
        }

        $weight = $row['CTS'] ?? 0;
        $buy_price = $row['NET_VALUE'] ?? 0;

        $final_price = $this->finalPrice($weight, $buy_price);
        $amount = $row['NET_VALUE'] ?? 0;

        // ===== SAFETY CHECK: final_price 0 wale record save nahi karna =====
        if ($final_price <= 0) {
            \Log::warning('mapDiamond: Skipping record with final_price 0', ['packet_no' => $stock_id]);
            return null;
        }

        $apiImage = trim((string) ($row['IMAGES'] ?? ''));
        $shapeSeq = $this->cleanString($row['SHAPE_SEQ'] ?? null);
        $colorSeq = $this->cleanString($row['COLOR_SEQ'] ?? null);

        // Try API image first, then fallback to local color+shape image
        $image = (!empty($apiImage) && $this->isValidImage1($apiImage))
            ? $apiImage
            : $this->getLocalColorAndShapeImage($shapeSeq, $colorSeq);

        $labcode_mp = null;

        if (!empty($row['LAB_SEQ']) && $this->cleanString($row['LAB_SEQ']) == 'MP') {
            $labcode_mp = 68;
        }

        return [
            'main' => [
                'code' => $stock_id,
                'images' => $image,
                'CertificateLink' => $this->cleanString($row['CERT_LINK']),
                'description' => $this->cleanString($row['DESCRIPTION']),
                'shape_master_id' => $this->getShapeMasterIdFromVariant($shapeSeq, $shapeMap),
                'iscertified' => !empty($row['LAB_SEQ']) ? 1 : 0,
                'shapecode' => $this->cleanString($row['SHAPE_SEQ']),
                'colorcode' => $this->cleanString($row['COLOR_SEQ']),
                'claritycode' => $this->cleanString($row['PURITY_SEQ']),
                'weight' => $weight,
                'labcode' => $this->cleanString($row['LAB_SEQ']),
                'labcode_mp' => $labcode_mp ?? null,
                'cutgrade' => $this->cleanString($row['CUT_SEQ']),
                'polish' => $this->cleanString($row['POLISH_SEQ']),
                'symmetry' => $this->cleanString($row['SYMM_SEQ']),
                'fluorescence' => $this->cleanString($row['FLS_SEQ']),
                'lwd' => $this->cleanString($row['LWD']),
                'depth_pct1' => $this->decimalOrNull($row['DEPTH_PER']),
                'table_pct' => $this->decimalOrNull($row['TABLE_PER']),
                'girdle' => $this->cleanString($row['GIRDLE']),
                'girdle_pct' => $this->decimalOrNull($row['GIRDLE_PER']),
                'crown_angle' => $this->decimalOrNull($row['CROWN_ANGLE']),
                'crown_height' => $this->decimalOrNull($row['CROWN_HEIGHT']),
                'pavilion_angle' => $this->decimalOrNull($row['PAVILLION_ANGLE']),
                'pavilion_depth' => $this->decimalOrNull($row['PAVILLION_HEIGHT']),
                'star_length' => $this->decimalOrNull($row['STAR']),
                'synthetic' => 'No',
                'shade' => $this->cleanString($row['Shade']),
                'eyeclean' => $this->cleanString($row['EYE_CLEAN']),
                'bgm' => $this->cleanString($row['BGM']),
                'center_inclusion' => $this->cleanString($row['CENTER_FEATHER']),
                'black_inclusion' => $this->cleanString($row['CENTER_NATTS']),
                'cost' => $this->decimalOrNull($amount),
                'rapprice' => $this->decimalOrNull($row['RATE']),
                'price1' => $this->decimalOrNull($final_price),
                'buy_price' => $buy_price,
                'origin' => $this->cleanString($row['COUNTRY_OF_ORIGIN']),
                'brand' => $this->cleanString($row['Company']),
                'certificate_notes' => $this->cleanString($row['REPORT_COMMENTS']),
                'type' => 'Lab Grown',
                'vendoritem' => $stock_id,
                'vendor_id' => $vendor_id,
                'video_link' => $this->cleanString($row['DNA_LINK']),
                'threed_link' => $image,
                'onhandweight' => $weight,
                'final_price' => $final_price,
                'milky' => $this->cleanString($row['MILKY']),
                'ratio_value' => $this->decimalOrNull($row['Ratio']),
                'key_to_symbols' => $this->cleanString($row['KEY_TO_SYMBOLS']),
                'side_feather' => $this->cleanString($row['SIDE_FEATHER']),
                'side_natts' => $this->cleanString($row['SIDE_NATTS']),
                'brilliancy' => $this->cleanString($row['BRILLIANCY']),
                'vshape_seq' => $this->cleanString($row['VSHAPE_SEQ']),
                'vlab_seq' => $this->cleanString($row['VLAB_SEQ']),
                'stage' => $this->cleanString($row['Stage']),
                'vcolor_seq' => $this->cleanString($row['VCOLOR_SEQ']),
                'vpurity_seq' => $this->cleanString($row['VPURITY_SEQ']),
                'vcut_seq' => $this->cleanString($row['VCUT_SEQ']),
                'vpolish_seq' => $this->cleanString($row['VPOLISH_SEQ']),
                'vsymm_seq' => $this->cleanString($row['VSYMM_SEQ']),
                'vfls_seq' => $this->cleanString($row['VFLS_SEQ']),
                'short_name' => $this->cleanString($row['SHORT_NAME']),
                'lab_tooltip' => $this->cleanString($row['LAB_TOOLTIP']),
                'ha' => $this->decimalOrNull($row['HA']),
                'real_image' => $this->cleanString($row['REAL_IMAGE']),
                'heart_image' => $this->cleanString($row['HEART_IMAGE']),
                'plotting_image' => $this->cleanString($row['PLOTTING_IMAGE']),
                'asset_scope_image' => $this->cleanString($row['ASSET_SCOPE_IMAGE']),
                'video_image' => $this->cleanString($row['VIDEO_IMAGE']),
                'sync_flag' => 1
            ],

            'bt' => [
                'packet_no' => $stock_id,
                'images' => $image,
                'video_image' => $this->cleanValue($row['VIDEO_IMAGE']),
                'sync_flag' => 1
            ]
        ];
    }

    public function diamondslab()
    {
        /*
         * Dispatches the import to a queue job so this HTTP request
         * returns immediately (fixes Gateway Timeout on large imports).
         * A queue worker must be running for the job to actually process
         * — see cron / supervisor setup notes.
         */

        \App\Jobs\ImportDiamondsJob::dispatch();

        return response()->json([
            'status' => true,
            'message' => 'Diamond import has been queued and will run in the background.',
        ]);
    }

    /**
     * ⭐ IMPROVED: Get local image from /public/assets/color/ folder
     * 
     * Your existing folder structure:
     * /public/assets/color/
     * ├── round-yellow.jpg
     * ├── round-blue.jpg
     * ├── cushion-pink.jpg
     * ├── heart-green.jpg
     * └── ... (all combinations)
     * 
     * Filename pattern: {shape}-{color}.jpg or .png
     */
    private function getLocalColorAndShapeImage($shape, $color = null)
    {
        if (empty($shape)) {
            \Log::warning('getLocalColorAndShapeImage: shape is empty');
            return asset('assets/color/no_image.jpg');
        }

        $shapeMap = $this->getShapeToFilenameMap();
        $colorMap = $this->getColorNameMap();

        // Get shape filename (round, cushion, heart, etc.)
        $shapeCode = strtoupper(trim((string) $shape));
        $shapeFileName = $shapeMap[$shapeCode] ?? null;

        if (!$shapeFileName) {
            \Log::warning('getLocalColorAndShapeImage: shape not found in map', ['shape' => $shapeCode]);
            return asset('assets/color/no_image.jpg');
        }

        // Get color filename (yellow, blue, pink, etc.)
        $colorCode = strtoupper(trim((string) $color));
        $colorFileName = $colorMap[$colorCode] ?? null;

        // ===== STEP 1: Try {shape}-{color}.jpg =====
        if (!empty($colorFileName)) {
            $fileName = $shapeFileName . '-' . $colorFileName . '.jpg';
            $path = 'assets/color/' . $fileName;

            if (file_exists(public_path($path))) {
                \Log::info('Found color+shape JPG', ['shape' => $shapeFileName, 'color' => $colorFileName, 'file' => $fileName]);
                return asset($path);
            }

            // ===== STEP 1b: Try {shape}-{color}.png (if JPG not found) =====
            $fileName = $shapeFileName . '-' . $colorFileName . '.png';
            $path = 'assets/color/' . $fileName;

            if (file_exists(public_path($path))) {
                \Log::info('Found color+shape PNG', ['shape' => $shapeFileName, 'color' => $colorFileName, 'file' => $fileName]);
                return asset($path);
            }

            \Log::warning('Color+shape image not found', ['shape' => $shapeFileName, 'color' => $colorFileName]);
        }

        // ===== STEP 2: Try {shape}.jpg as fallback =====
        $fileName = $shapeFileName . '.jpg';
        $path = 'assets/color/' . $fileName;

        if (file_exists(public_path($path))) {
            \Log::info('Using shape-only JPG fallback', ['shape' => $shapeFileName, 'file' => $fileName]);
            return asset($path);
        }

        // ===== STEP 2b: Try {shape}.png as fallback =====
        $fileName = $shapeFileName . '.png';
        $path = 'assets/color/' . $fileName;

        if (file_exists(public_path($path))) {
            \Log::info('Using shape-only PNG fallback', ['shape' => $shapeFileName, 'file' => $fileName]);
            return asset($path);
        }

        // ===== STEP 3: Ultimate fallback =====
        \Log::warning('No image found, using ultimate fallback', ['shape' => $shapeFileName, 'color' => $colorFileName]);
        return asset('assets/color/no_image.jpg');
    }

    /**
     * Legacy method kept for backwards compatibility
     */
    private function getLocalShapeImage($shape, $color = null)
    {
        return $this->getLocalColorAndShapeImage($shape, $color);
    }

    private function sendImportAlert($subject, $message)
    {
        // Implement your alert logic here (email, slack, etc)
    }
}