<?php

namespace App\Http\Controllers;

use App\Models\StockMarket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
class StockMarketController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    public function randay (){
     return   rand(1, 100);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $allStocks = StockMarket::all();
        $results = [
            'success' => [],
            'failed' => []
        ];

        // Marketstack API key - replace with your key
        $apiKey = env('MARKETSTACK_API_KEY','7e5e0ea2e506ec871241f56e14f1aab3');

        try {
            // Get all stock symbols
            $symbols = $allStocks->pluck('short_name')->implode(',');
            
            // Make a single API call to get all stock prices
            $url = "http://api.marketstack.com/v1/eod/latest?access_key={$apiKey}&symbols={$symbols}&exchange=XNYS,XNAS";
            
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => [
                    'Accept: application/json'
                ]
            ]);

            $response = curl_exec($ch);
            $err = curl_error($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            curl_close($ch);

            if ($err) {
                throw new \Exception("Curl Error: " . $err);
            }

            if ($httpCode !== 200) {
                throw new \Exception("HTTP Error: " . $httpCode);
            }

            $json_response = json_decode($response);
            
            if (empty($json_response) || !isset($json_response->data)) {
                throw new \Exception("Invalid response format");
            }

            // Create a lookup array for quick access to stock data
            $stockData = [];
            foreach ($json_response->data as $quote) {
                $stockData[$quote->symbol] = $quote;
            }

            // Update all stocks
            foreach ($allStocks as $stock) {
                try {
                    if (!isset($stockData[$stock->short_name])) {
                        throw new \Exception("No data available for symbol");
                    }

                    $quote = $stockData[$stock->short_name];
                    
                    // Update all price-related fields
                    $updateData = [
                        'priceUsd' => floatval($quote->close),
                        'high_price' => floatval($quote->high),
                        'low_price' => floatval($quote->low),
                        'current_price' => floatval($quote->close),
                        'change_price' => floatval($quote->close - $quote->open),
                        'change_percentage' => round((($quote->close - $quote->open) / $quote->open) * 100, 2)
                    ];

                    // Log the update data for debugging
                    \Log::info("Attempting to update stock {$stock->short_name} with data:", $updateData);

                    try {
                        // Use updateOrCreate to ensure the record exists and is updated
                        $updatedStock = StockMarket::where('short_name', $stock->short_name)
                            ->update($updateData);
                        
                        if ($updatedStock === false) {
                            throw new \Exception("Database update failed");
                        }

                        // Verify the update
                        $verifyStock = StockMarket::where('short_name', $stock->short_name)->first();
                        if (!$verifyStock || $verifyStock->current_price != floatval($quote->close)) {
                            throw new \Exception("Update verification failed");
                        }

                        // Log the update result
                        \Log::info("Successfully updated {$stock->short_name} with price: {$verifyStock->current_price}");

                        $results['success'][] = [
                            'symbol' => $stock->short_name,
                            'price' => floatval($quote->close),
                            'change' => floatval($quote->close - $quote->open),
                            'change_percentage' => round((($quote->close - $quote->open) / $quote->open) * 100, 2)
                        ];

                    } catch (\Exception $dbError) {
                        \Log::error("Database error for {$stock->short_name}: " . $dbError->getMessage());
                        $results['failed'][] = [
                            'symbol' => $stock->short_name,
                            'error' => "Database update failed: " . $dbError->getMessage()
                        ];
                    }

                } catch (\Exception $e) {
                    $results['failed'][] = [
                        'symbol' => $stock->short_name,
                        'error' => $e->getMessage()
                    ];
                    \Log::error("Failed to update {$stock->short_name}: " . $e->getMessage());
                }
            }

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to fetch stock data',
                'error' => $e->getMessage()
            ], 500);
        }

        return response()->json([
            'status' => 'completed',
            'message' => 'Stock price update process completed',
            'summary' => [
                'total_stocks' => count($allStocks),
                'successful_updates' => count($results['success']),
                'failed_updates' => count($results['failed'])
            ],
            'results' => $results
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\StockMarket  $stockMarket
     * @return \Illuminate\Http\Response
     */
    public function show(StockMarket $stockMarket)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\StockMarket  $stockMarket
     * @return \Illuminate\Http\Response
     */
    public function edit(StockMarket $stockMarket)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\StockMarket  $stockMarket
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, StockMarket $stockMarket)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\StockMarket  $stockMarket
     * @return \Illuminate\Http\Response
     */
    public function destroy(StockMarket $stockMarket)
    {
        //
    }

    public function populateStocks()
    {
        $stocks = [
            // Technology
            ['name' => 'Apple Inc.', 'short_name' => 'AAPL', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Technology'],
            ['name' => 'Microsoft Corporation', 'short_name' => 'MSFT', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Technology'],
            ['name' => 'Alphabet Inc.', 'short_name' => 'GOOGL', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Technology'],
            ['name' => 'Amazon.com Inc.', 'short_name' => 'AMZN', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Technology'],
            ['name' => 'Meta Platforms Inc.', 'short_name' => 'META', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Technology'],
            ['name' => 'NVIDIA Corporation', 'short_name' => 'NVDA', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Technology'],
            ['name' => 'Tesla Inc.', 'short_name' => 'TSLA', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Technology'],
            ['name' => 'Netflix Inc.', 'short_name' => 'NFLX', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Technology'],
            ['name' => 'Adobe Inc.', 'short_name' => 'ADBE', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Technology'],
            ['name' => 'Salesforce Inc.', 'short_name' => 'CRM', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Technology'],
            
            // Financial Services
            ['name' => 'JPMorgan Chase & Co.', 'short_name' => 'JPM', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Financial Services'],
            ['name' => 'Bank of America Corp', 'short_name' => 'BAC', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Financial Services'],
            ['name' => 'Visa Inc.', 'short_name' => 'V', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Financial Services'],
            ['name' => 'Mastercard Inc.', 'short_name' => 'MA', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Financial Services'],
            ['name' => 'Goldman Sachs Group', 'short_name' => 'GS', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Financial Services'],
            
            // Healthcare
            ['name' => 'Johnson & Johnson', 'short_name' => 'JNJ', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Healthcare'],
            ['name' => 'Pfizer Inc.', 'short_name' => 'PFE', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Healthcare'],
            ['name' => 'Merck & Co. Inc.', 'short_name' => 'MRK', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Healthcare'],
            ['name' => 'AbbVie Inc.', 'short_name' => 'ABBV', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Healthcare'],
            ['name' => 'UnitedHealth Group', 'short_name' => 'UNH', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Healthcare'],
            
            // Consumer Goods
            ['name' => 'Procter & Gamble', 'short_name' => 'PG', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Consumer Goods'],
            ['name' => 'Coca-Cola Company', 'short_name' => 'KO', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Consumer Goods'],
            ['name' => 'PepsiCo Inc.', 'short_name' => 'PEP', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Consumer Goods'],
            ['name' => 'Nike Inc.', 'short_name' => 'NKE', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Consumer Goods'],
            ['name' => 'Walmart Inc.', 'short_name' => 'WMT', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Consumer Goods'],
            
            // Energy
            ['name' => 'Exxon Mobil Corp', 'short_name' => 'XOM', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Energy'],
            ['name' => 'Chevron Corporation', 'short_name' => 'CVX', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Energy'],
            ['name' => 'Shell PLC', 'short_name' => 'SHEL', 'country' => 'UK', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Energy'],
            ['name' => 'BP p.l.c.', 'short_name' => 'BP', 'country' => 'UK', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Energy'],
            ['name' => 'TotalEnergies SE', 'short_name' => 'TTE', 'country' => 'France', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Energy'],
            
            // Industrial
            ['name' => 'Boeing Company', 'short_name' => 'BA', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Industrial'],
            ['name' => 'General Electric', 'short_name' => 'GE', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Industrial'],
            ['name' => 'Honeywell International', 'short_name' => 'HON', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Industrial'],
            ['name' => '3M Company', 'short_name' => 'MMM', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Industrial'],
            ['name' => 'Caterpillar Inc.', 'short_name' => 'CAT', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Industrial'],
            
            // Communication Services
            ['name' => 'Walt Disney Company', 'short_name' => 'DIS', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Communication Services'],
            ['name' => 'AT&T Inc.', 'short_name' => 'T', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Communication Services'],
            ['name' => 'Verizon Communications', 'short_name' => 'VZ', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Communication Services'],
            ['name' => 'Comcast Corporation', 'short_name' => 'CMCSA', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Communication Services'],
            ['name' => 'T-Mobile US Inc.', 'short_name' => 'TMUS', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Communication Services'],
            
            // Materials
            ['name' => 'BHP Group Limited', 'short_name' => 'BHP', 'country' => 'Australia', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Materials'],
            ['name' => 'Rio Tinto Group', 'short_name' => 'RIO', 'country' => 'UK', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Materials'],
            ['name' => 'Freeport-McMoRan Inc.', 'short_name' => 'FCX', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Materials'],
            ['name' => 'Newmont Corporation', 'short_name' => 'NEM', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Materials'],
            ['name' => 'Dow Inc.', 'short_name' => 'DOW', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Materials'],
            
            // Real Estate
            ['name' => 'American Tower Corp', 'short_name' => 'AMT', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Real Estate'],
            ['name' => 'Prologis Inc.', 'short_name' => 'PLD', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Real Estate'],
            ['name' => 'Simon Property Group', 'short_name' => 'SPG', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Real Estate'],
            ['name' => 'Digital Realty Trust', 'short_name' => 'DLR', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Real Estate'],
            ['name' => 'Welltower Inc.', 'short_name' => 'WELL', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Real Estate'],
            
            // Utilities
            ['name' => 'NextEra Energy Inc.', 'short_name' => 'NEE', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Utilities'],
            ['name' => 'Duke Energy Corp', 'short_name' => 'DUK', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Utilities'],
            ['name' => 'Southern Company', 'short_name' => 'SO', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Utilities'],
            ['name' => 'Dominion Energy', 'short_name' => 'D', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE', 'sector' => 'Utilities'],
            ['name' => 'American Electric Power', 'short_name' => 'AEP', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'Utilities'],
            
            // ETFs
            ['name' => 'SPDR S&P 500 ETF', 'short_name' => 'SPY', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE Arca', 'sector' => 'ETF'],
            ['name' => 'Invesco QQQ Trust', 'short_name' => 'QQQ', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NASDAQ', 'sector' => 'ETF'],
            ['name' => 'iShares Russell 2000 ETF', 'short_name' => 'IWM', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE Arca', 'sector' => 'ETF'],
            ['name' => 'Vanguard Total Stock Market ETF', 'short_name' => 'VTI', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE Arca', 'sector' => 'ETF'],
            ['name' => 'Vanguard S&P 500 ETF', 'short_name' => 'VOO', 'country' => 'USA', 'ccy' => 'USD', 'exch' => 'NYSE Arca', 'sector' => 'ETF']
        ];

        try {
            // Clear existing records if needed
            // StockMarket::truncate();

            // Insert new records
            foreach ($stocks as $stock) {
                StockMarket::create($stock);
            }

            return response()->json([
                'status' => 'success',
                'message' => 'Stocks database populated successfully',
                'total_stocks' => count($stocks)
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Failed to populate stocks database',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
