<?php 
   session_start();
   ini_set('display_errors', 1);
   ini_set('display_startup_errors', 1);
   error_reporting(E_ALL);
   mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
   
   include("header.php"); // Database connection
   
   if (!isset($_SESSION['customerid'])) {
       header('Location:login.php?error=nologin');
       exit;
   }
   
   // --- CONFIGURATION ---
   $apiKey = "d5fq5thr01qnjhodtm9gd5fq5thr01qnjhodtma0"; 
   
   // --- HELPER FUNCTION: Fetch Real Stock Data ---
   function getStockData($symbol, $apiKey) {
       $url = "https://finnhub.io/api/v1/quote?symbol=" . $symbol . "&token=" . $apiKey;
       
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $url);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_TIMEOUT, 2); 
       $response = curl_exec($ch);
       curl_close($ch);
       
       $data = json_decode($response, true);
       
       if (!isset($data['c'])) {
           return ['price' => 0.00, 'change' => 0.00, 'percent' => 0.00];
       }
       
       return [
           'price' => $data['c'],       
           'change' => $data['d'],      
           'percent' => $data['dp']     
       ];
   }

   // --- HELPER FUNCTION: Get Total Shares Owned ---
   function getSharesOwned($con, $customerid, $symbol) {
       $stmt = $con->prepare("SELECT SUM(quantity) as total_shares FROM stock_orders WHERE customerid=? AND symbol=?");
       $stmt->bind_param("ss", $customerid, $symbol);
       $stmt->execute();
       $result = $stmt->get_result();
       $row = $result->fetch_assoc();
       $stmt->close();
       return $row['total_shares'] ? intval($row['total_shares']) : 0;
   }

   // Fetch User Data & Balance
   $stmt = $con->prepare("SELECT * FROM accounts WHERE customerid=?");
   $stmt->bind_param("s", $_SESSION['customerid']);
   $stmt->execute();
   $result = $stmt->get_result();
   $rowrec = $result->fetch_assoc();
   $stmt->close();
   
   // --- HANDLE STOCK TRANSACTIONS ---
   $alertScript = ""; 
   $date = date("Y-m-d H:i:s");
   
   if (isset($_POST['buy_stock'])) {
       $symbol = htmlspecialchars($_POST['stock_symbol']);
       $stockName = htmlspecialchars($_POST['stock_name']);
       $price = floatval($_POST['stock_price']);
       $qty = intval($_POST['stock_qty']);
       $total_cost = $price * $qty;
       $current_balance = floatval($rowrec['accountbalance']);

       if ($total_cost <= 0) {
            $alertScript = "alert('Error: Invalid Amount');";
       } elseif ($total_cost > $current_balance) {
            $shortfall = number_format($total_cost, 2);
            $alertScript = "alert('Insufficient Funds: You need $$shortfall to buy these shares.');";
       } else {
           $new_balance = $current_balance - $total_cost;
           $update = $con->prepare("UPDATE accounts SET accountbalance=? WHERE customerid=?");
           $update->bind_param("ds", $new_balance, $_SESSION['customerid']);
           if ($update->execute()) {
               $update->close();
               $insert = $con->prepare("INSERT INTO stock_orders (customerid, symbol, stock_name, price, quantity, total_cost, date) VALUES (?, ?, ?, ?, ?, ?, ?)");
               $insert->bind_param("sssddds", $_SESSION['customerid'], $symbol, $stockName, $price, $qty, $total_cost, $date);
               $insert->execute();
               $insert->close();
               $alertScript = "alert('Purchase Successful!'); window.location.href='stocks.php';";
           }
       }
   }

   if (isset($_POST['sell_stock'])) {
        $symbol = htmlspecialchars($_POST['stock_symbol']);
        $stockName = htmlspecialchars($_POST['stock_name']);
        $price = floatval($_POST['stock_price']);
        $qty = intval($_POST['stock_qty']);
        $total_value = $price * $qty; 
        $owned = getSharesOwned($con, $_SESSION['customerid'], $symbol);
        if ($qty <= 0) {
             $alertScript = "alert('Error: Invalid Quantity');";
        } elseif ($qty > $owned) {
             $alertScript = "alert('Insufficient Shares.');";
        } else {
            $current_balance = floatval($rowrec['accountbalance']);
            $new_balance = $current_balance + $total_value;
            $update = $con->prepare("UPDATE accounts SET accountbalance=? WHERE customerid=?");
            $update->bind_param("ds", $new_balance, $_SESSION['customerid']);
            if ($update->execute()) {
                $update->close();
                $sell_qty = -$qty; 
                $insert = $con->prepare("INSERT INTO stock_orders (customerid, symbol, stock_name, price, quantity, total_cost, date) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $insert->bind_param("sssddds", $_SESSION['customerid'], $symbol, $stockName, $price, $sell_qty, $total_value, $date);
                $insert->execute();
                $insert->close();
                $alertScript = "alert('Sold Successfully!'); window.location.href='stocks.php';";
            }
        }
   }

   // --- FETCH PORTFOLIO & HISTORY ---
   $portfolio_query = "SELECT symbol, stock_name, SUM(quantity) as shares_owned, SUM(CASE WHEN quantity > 0 THEN total_cost ELSE 0 END) / NULLIF(SUM(CASE WHEN quantity > 0 THEN quantity ELSE 0 END), 0) as avg_buy_price FROM stock_orders WHERE customerid = ? GROUP BY symbol HAVING shares_owned > 0";
   $p_stmt = $con->prepare($portfolio_query);
   $p_stmt->bind_param("s", $_SESSION['customerid']);
   $p_stmt->execute();
   $portfolio_result = $p_stmt->get_result();

   $history_query = "SELECT * FROM stock_orders WHERE customerid = ? ORDER BY date DESC";
   $h_stmt = $con->prepare($history_query);
   $h_stmt->bind_param("s", $_SESSION['customerid']);
   $h_stmt->execute();
   $history_result = $h_stmt->get_result();

   // Live Stocks
   $symbols = [['symbol' => 'AAPL', 'name' => 'Apple Inc.', 'icon' => 'bx bxl-apple'], ['symbol' => 'TSLA', 'name' => 'Tesla, Inc.', 'icon' => 'bx bxs-car'], ['symbol' => 'NVDA', 'name' => 'NVIDIA Corp', 'icon' => 'bx bx-chip'], ['symbol' => 'AMZN', 'name' => 'Amazon.com', 'icon' => 'bx bxl-amazon'], ['symbol' => 'GOOGL', 'name' => 'Alphabet Inc.', 'icon' => 'bx bxl-google']];
   $stocks = [];
   $current_prices = []; 

   foreach ($symbols as $s) {
       $apiData = getStockData($s['symbol'], $apiKey);
       $current_prices[$s['symbol']] = $apiData['price']; 
       $stocks[] = array_merge($s, ['price' => $apiData['price'], 'change' => number_format($apiData['change'], 2), 'trend' => ($apiData['change'] >= 0 ? 'up' : 'down')]);
   }

   $cur = '$'; 
   $q = mysqli_query($con, "SELECT currency FROM system_settings LIMIT 1");
   if($r = mysqli_fetch_assoc($q)) $cur = $r['currency'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Stocks & Trading | <?php echo $sbank ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/app.min.css" rel="stylesheet" type="text/css" />
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    
    <style>
    :root {
        --primary-purple: #003399; 
        --dark-purple: #005D9D;
        --soft-purple-bg: #e6efff; 
        --bg-body: #f8fafc;
        --text-main: #0f172a;
    }

    body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-body); color: var(--text-main); }
    .page-content { padding-top: 80px; padding-bottom: 60px; }

    /* --- MOBILE FORCED WHITE MODAL --- */
    .modal-content { 
        background-color: #ffffff !important; 
        border-radius: 24px !important; 
        border: none !important; 
    }
    .modal-body { background-color: #ffffff !important; border-bottom-left-radius: 24px; border-bottom-right-radius: 24px; }
    .modal-body h4, .modal-body h5, .modal-body .fw-bold, .modal-body .text-dark, .modal-body label { color: #0f172a !important; }
    .modal-body .text-secondary { color: #64748b !important; }
    .modal-body .bg-light { background-color: #f8f9fa !important; border: 1px solid #e2e8f0 !important; }

    .balance-pill { background: white; border: 1px solid #e2e8f0; padding: 10px 20px; border-radius: 50px; font-weight: 700; display: inline-flex; align-items: center; gap: 10px; }
    .market-card { background: linear-gradient(135deg, #001a4d 0%, #003399 100%); border-radius: 24px; padding: 30px; color: white; margin-bottom: 40px; box-shadow: 0 20px 25px -5px rgba(0, 51, 153, 0.3); }
    .stock-row { background: white; border-radius: 20px; padding: 20px; margin-bottom: 15px; border: 1px solid #e2e8f0; display: flex; align-items: center; justify-content: space-between; }
    .stock-icon-box { width: 50px; height: 50px; background: var(--soft-purple-bg); color: var(--primary-purple); border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 24px; margin-right: 15px; }
    .btn-buy { background: var(--primary-purple); color: white; border: none; padding: 8px 20px; border-radius: 12px; font-weight: 600; }
    .btn-sell { background: #fef2f2; color: #ef4444; border: 1px solid #fecaca; padding: 6px 14px; border-radius: 10px; font-weight: 600; }
    .history-card { background: white; border-radius: 24px; border: 1px solid #e2e8f0; padding: 20px; margin-bottom: 30px; overflow: hidden; }
    .modal-header-custom { padding: 20px 30px; text-align: center; border-top-left-radius: 24px; border-top-right-radius: 24px; }
    .modal-header-buy { background: var(--soft-purple-bg) !important; }
    .modal-header-sell { background: #fef2f2 !important; }

    @media (max-width: 768px) {
        .table-mobile-responsive thead { display: none; }
        .table-mobile-responsive tr { display: block; background: #fff; border-radius: 12px; margin-bottom: 15px; border: 1px solid #e2e8f0; padding: 10px; }
        .table-mobile-responsive td { display: flex; justify-content: space-between; padding: 10px 5px; border-bottom: 1px solid #f1f5f9; }
        .table-mobile-responsive td::before { content: attr(data-label); font-weight: 700; color: #64748b; font-size: 0.75rem; text-transform: uppercase; }
    }
</style>
</head>

<body>
    <div id="layout-wrapper">
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h2 class="mb-1 fw-800 text-dark">Market & Stocks</h2>
                        </div>
                        <div class="col-md-6 text-md-end">
                            <div class="balance-pill">
                                <span class="text-secondary small">Balance</span>
                                <span class="text-dark fs-5"><?php echo $cur . number_format($rowrec['accountbalance'], 2); ?></span>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-5">
                        <div class="col-12">
                            <div class="market-card">
                                <h2 class="fw-800 mb-0">S&P 500 <span class="fs-6 text-success fw-bold bg-success-subtle px-2 rounded ms-2">Live</span></h2>
                                <div id="marketChart" style="min-height: 150px;"></div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-7">
                            <h4 class="fw-800 text-dark mb-4">Live Market</h4>
                            <?php foreach($stocks as $stock): ?>
                            <div class="stock-row">
                                <div class="d-flex align-items-center">
                                    <div class="stock-icon-box"><i class="<?php echo $stock['icon']; ?>"></i></div>
                                    <div><h5 class="fw-bold mb-0"><?php echo $stock['symbol']; ?></h5><small class="text-secondary"><?php echo $stock['name']; ?></small></div>
                                </div>
                                <div class="text-end d-flex align-items-center gap-3">
                                    <h5 class="fw-bold mb-0 text-dark">$<?php echo number_format($stock['price'], 2); ?></h5>
                                    <button class="btn-buy" onclick="openBuyModal('<?php echo $stock['symbol']; ?>', '<?php echo $stock['name']; ?>', '<?php echo $stock['price']; ?>')">Buy</button>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="col-lg-5">
                            <h4 class="fw-800 text-dark mb-4">Portfolio</h4>
                            <div class="history-card">
                                <div class="table-responsive">
                                    <table class="table table-modern table-mobile-responsive align-middle mb-0">
                                        <thead>
                                            <tr>
                                                <th>Asset</th>
                                                <th class="text-center">Owned</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($portfolio_result->num_rows > 0) { 
                                                while($p = $portfolio_result->fetch_assoc()) { 
                                            ?>
                                            <tr>
                                                <td data-label="Asset">
                                                    <span class="fw-bold text-dark"><?php echo $p['symbol']; ?></span>
                                                </td>
                                                <td data-label="Owned" class="text-center fw-bold">
                                                    <?php echo $p['shares_owned']; ?>
                                                </td>
                                                <td data-label="Action">
                                                    <button class="btn-sell" onclick="openSellModal('<?php echo $p['symbol']; ?>', '<?php echo $p['stock_name']; ?>', '<?php echo $current_prices[$p['symbol']] ?? 0; ?>', '<?php echo $p['shares_owned']; ?>')">Sell</button>
                                                </td>
                                            </tr>
                                            <?php } 
                                            } else { 
                                                echo '<tr><td colspan="3" class="text-center py-3 text-muted">No stocks owned.</td></tr>'; 
                                            } ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row mt-4">
                        <div class="col-12">
                            <h4 class="fw-800 text-dark mb-4">History</h4>
                            <div class="history-card">
                                <table class="table table-mobile-responsive align-middle mb-0">
                                    <thead><tr><th>Type</th><th>Symbol</th><th>Qty</th><th>Total</th><th>Date</th></tr></thead>
                                    <tbody>
                                        <?php while($h = $history_result->fetch_assoc()) { 
                                            $type = ($h['quantity'] < 0) ? '<span class="badge bg-danger-subtle text-danger">SELL</span>' : '<span class="badge bg-success-subtle text-success">BUY</span>';
                                        ?>
                                        <tr>
                                            <td data-label="Type"><?php echo $type; ?></td>
                                            <td data-label="Symbol"><?php echo $h['symbol']; ?></td>
                                            <td data-label="Qty"><?php echo abs($h['quantity']); ?></td>
                                            <td data-label="Total"><?php echo $cur . number_format($h['total_cost'], 2); ?></td>
                                            <td data-label="Date" class="small"><?php echo date("M d, Y", strtotime($h['date'])); ?></td>
                                        </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div> 
            </div>
        </div>
    </div>

    <div class="modal fade" id="buyStockModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header-custom modal-header-buy"><h5 class="fw-800 mb-0">Buy Stock</h5></div>
                <div class="modal-body p-4">
                    <form method="POST">
                        <div class="d-flex align-items-center mb-4 p-3 bg-light rounded-4">
                            <div class="stock-icon-box bg-white shadow-sm" style="margin-right:15px;"><i class='bx bx-up-arrow-circle'></i></div>
                            <div class="ms-1"><h4 class="fw-bold mb-0" id="buy-modal-stock-symbol">AAPL</h4><span class="text-secondary small" id="buy-modal-stock-name">Apple Inc.</span></div>
                            <div class="ms-auto text-end"><span class="fw-bold fs-5">$<span id="buy-modal-stock-price">0.00</span></span></div>
                        </div>
                        <input type="hidden" name="stock_symbol" id="buy-input-symbol"><input type="hidden" name="stock_name" id="buy-input-name"><input type="hidden" name="stock_price" id="buy-input-price">
                        <div class="mb-4"><label class="form-label fw-bold text-uppercase small">Quantity to Buy</label><input type="number" name="stock_qty" id="buy-stock-qty" class="form-control form-control-lg" value="1" min="1" oninput="calculateBuyTotal()"></div>
                        <div class="d-flex justify-content-between align-items-center mb-4 pt-3 border-top"><span class="text-secondary fw-bold">Estimated Cost</span><span class="fs-3 fw-800" style="color:#003399;">$<span id="buy-total-cost">0.00</span></span></div>
                        <button style="background-color: #003399, color: white;" type="submit" name="buy_stock" class="btn w-100 rounded-pill py-3 fw-bold">Confirm Purchase</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="sellStockModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header-custom modal-header-sell"><h5 class="fw-800 mb-0 text-danger">Sell Stock</h5></div>
                <div class="modal-body p-4">
                    <form method="POST">
                        <div class="d-flex align-items-center mb-4 p-3 bg-light rounded-4">
                            <div class="stock-icon-box bg-white shadow-sm" style="margin-right:15px;"><i class='bx bx-down-arrow-circle'></i></div>
                            <div class="ms-1"><h4 class="fw-bold mb-0" id="sell-modal-stock-symbol">AAPL</h4><span class="text-secondary small">You own: <b id="sell-modal-owned">0</b></span></div>
                            <div class="ms-auto text-end"><span class="fw-bold fs-5">$<span id="sell-modal-stock-price">0.00</span></span></div>
                        </div>
                        <input type="hidden" name="stock_symbol" id="sell-input-symbol"><input type="hidden" name="stock_name" id="sell-input-name"><input type="hidden" name="stock_price" id="sell-input-price">
                        <div class="mb-4"><label class="form-label fw-bold text-uppercase small">Quantity to Sell</label><input type="number" name="stock_qty" id="sell-stock-qty" class="form-control form-control-lg" value="1" min="1" oninput="calculateSellTotal()"></div>
                        <div class="d-flex justify-content-between align-items-center mb-4 pt-3 border-top"><span class="text-secondary fw-bold">Total Payout</span><span class="fs-3 fw-800 text-danger">$<span id="sell-total-cost">0.00</span></span></div>
                        <button type="submit" name="sell_stock" class="btn btn-danger w-100 rounded-pill py-3 fw-bold">Confirm Sale</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/apexcharts/apexcharts.min.js"></script>
    <script>
        <?php echo $alertScript; ?>
        function openBuyModal(symbol, name, price) {
            document.getElementById('buy-modal-stock-symbol').innerText = symbol;
            document.getElementById('buy-modal-stock-name').innerText = name;
            document.getElementById('buy-modal-stock-price').innerText = parseFloat(price).toFixed(2);
            document.getElementById('buy-input-symbol').value = symbol;
            document.getElementById('buy-input-name').value = name;
            document.getElementById('buy-input-price').value = price;
            document.getElementById('buy-stock-qty').value = 1;
            calculateBuyTotal();
            new bootstrap.Modal(document.getElementById('buyStockModal')).show();
        }
        function calculateBuyTotal() {
            const price = parseFloat(document.getElementById('buy-input-price').value) || 0;
            const qty = parseInt(document.getElementById('buy-stock-qty').value) || 0;
            document.getElementById('buy-total-cost').innerText = (price * qty).toLocaleString('en-US', {minimumFractionDigits: 2});
        }
        function openSellModal(symbol, name, price, owned) {
            document.getElementById('sell-modal-stock-symbol').innerText = symbol;
            document.getElementById('sell-modal-owned').innerText = owned;
            document.getElementById('sell-modal-stock-price').innerText = parseFloat(price).toFixed(2);
            document.getElementById('sell-input-symbol').value = symbol;
            document.getElementById('sell-input-name').value = name;
            document.getElementById('sell-input-price').value = price;
            document.getElementById('sell-stock-qty').value = 1;
            calculateSellTotal();
            new bootstrap.Modal(document.getElementById('sellStockModal')).show();
        }
        function calculateSellTotal() {
            const price = parseFloat(document.getElementById('sell-input-price').value) || 0;
            const qty = parseInt(document.getElementById('sell-stock-qty').value) || 0;
            document.getElementById('sell-total-cost').innerText = (price * qty).toLocaleString('en-US', {minimumFractionDigits: 2});
        }

        document.addEventListener("DOMContentLoaded", function() {
            var options = {
                chart: { height: 180, type: 'area', toolbar: { show: false }, sparkline: { enabled: true } },
                colors: ['#a78bfa'],
                stroke: { curve: 'smooth', width: 2 },
                series: [{ name: 'Value', data: [130, 145, 135, 150, 160, 155, 170, 180, 175, 190] }],
                tooltip: { theme: 'dark' }
            };
            new ApexCharts(document.querySelector("#marketChart"), options).render();
        });
    </script>
</body>
</html>