<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include("check_installation.php");
include("fetch_settings.php");

if (!isset($_SESSION["adminid"])) {
    header("Location: login.php");
    exit;
}

// Pagination setup
$records_per_page = 10;
$current_page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($current_page - 1) * $records_per_page;

// Fetch total number of stock orders
$total_result = $con->query("SELECT COUNT(*) FROM stock_orders");
$total_rows = $total_result->fetch_row()[0];
$total_pages = ceil($total_rows / $records_per_page);

// Fetch Stock Orders with Customer Details using JOIN
$sql = "SELECT 
            so.id, so.symbol, so.stock_name, so.price, so.quantity, so.total_cost, so.status, so.date,
            c.firstname, c.lastname, c.email, c.image
        FROM stock_orders so
        JOIN customers c ON so.customerid = c.customerid
        ORDER BY so.date DESC 
        LIMIT $records_per_page OFFSET $offset";

$result = $con->query($sql);
$stock_orders = $result->fetch_all(MYSQLI_ASSOC);
$result->free();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Manage Stock Orders</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <link rel="icon" href="../<?= htmlspecialchars($system_favicon); ?>" type="image/<?= pathinfo($system_favicon, PATHINFO_EXTENSION); ?>">

    <link rel="preconnect" href="https://fonts.googleapis.com/">
    <link rel="preconnect" href="https://fonts.gstatic.com/" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="assets/vendor/font-awesome/css/all.min.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/bootstrap-icons/bootstrap-icons.css">
    <link rel="stylesheet" type="text/css" href="assets/vendor/overlay-scrollbar/css/overlayscrollbars.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" type="text/css" href="assets/css/style.css">

    <style>
        :root { --primary-purple: #7c3aed; --dark-purple: #5b21b6; --soft-purple: #f5f3ff; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: #f8fafc; }
        
        .card { border: none; border-radius: 16px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { background: white; border-bottom: 1px solid #f1f5f9; padding: 20px 24px; }
        .card-title { font-weight: 700; color: #1e293b; margin: 0; }
        
        /* Table Styles */
        .table thead th {
            background-color: #f8fafc;
            color: #64748b;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.75rem;
            letter-spacing: 0.5px;
            border-bottom: 1px solid #e2e8f0;
            padding: 16px;
        }
        .table tbody td {
            padding: 16px;
            vertical-align: middle;
            color: #334155;
            font-size: 0.9rem;
            border-bottom: 1px solid #f1f5f9;
        }
        
        /* Badges */
        .badge { padding: 6px 12px; border-radius: 6px; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; }
        .badge-completed { background-color: #dcfce7; color: #166534; }
        .badge-pending { background-color: #fff7ed; color: #9a3412; border: 1px solid #fdba74; }
        .badge-failed { background-color: #fee2e2; color: #991b1b; }
        
        /* User Info */
        .user-meta { display: flex; align-items: center; gap: 12px; }
        .user-avatar { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; background: var(--soft-purple); }
        .user-details h6 { margin: 0; font-weight: 700; font-size: 0.9rem; color: #1e293b; }
        .user-details span { font-size: 0.8rem; color: #64748b; }
        
        /* Stock Info */
        .stock-symbol { font-weight: 700; color: var(--primary-purple); background: var(--soft-purple); padding: 4px 8px; border-radius: 6px; font-size: 0.8rem; }
        .price-text { font-family: monospace; font-weight: 700; color: #0f172a; }
        
        .btn-print { background: var(--primary-purple); color: white; border: none; padding: 10px 20px; border-radius: 8px; font-weight: 600; transition: 0.3s; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; }
        .btn-print:hover { background: var(--dark-purple); color: white; transform: translateY(-2px); }
        
        .pagination .page-link { color: #64748b; border: none; margin: 0 2px; border-radius: 6px; }
        .pagination .page-item.active .page-link { background-color: var(--primary-purple); color: white; }
    </style>
</head>
<body>

<main>
    <?php include "include/sidebar.php" ?>
    <div class="page-content">
        <?php include "include/topbar.php" ?>
        <div class="page-content-wrapper p-xxl-4">

            <div class="row mb-4 align-items-center">
                <div class="col-12 col-md-6">
                    <h1 class="h3 mb-0 fw-bold text-dark">Stock Orders</h1>
                    <p class="text-muted mb-0">Track all customer stock purchases and sales.</p>
                </div>
                <div class="col-12 col-md-6 text-md-end mt-3 mt-md-0">
                    <a href="#" class="btn-print" onclick="window.print()">
                        <i class="fas fa-print"></i> Print Report
                    </a>
                </div>
            </div>

            <div class="card shadow-sm">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="card-title">Order History</h5>
                        <span class="badge bg-light text-dark border">Total Orders: <?= $total_rows ?></span>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table mb-0 align-middle">
                            <thead>
                                <tr>
                                    <th>Order ID</th>
                                    <th>Customer</th>
                                    <th>Stock</th>
                                    <th>Qty</th>
                                    <th>Price</th>
                                    <th>Total Cost</th>
                                    <th>Date</th>
                                    <th>Status</th>
                                    
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($stock_orders)): ?>
                                    <?php foreach ($stock_orders as $order): ?>
                                        <?php 
                                            // Handle status badge color
                                            $status_lower = strtolower($order['status']);
                                            $badge_class = 'badge-pending'; // Default
                                            if($status_lower == 'completed' || $status_lower == 'successful') $badge_class = 'badge-completed';
                                            elseif($status_lower == 'failed' || $status_lower == 'cancelled') $badge_class = 'badge-failed';
                                            
                                            // Handle Avatar
                                            $avatar = !empty($order['image']) ? '../assets/images/users/' . $order['image'] : 'assets/images/avatar-1.jpg';
                                        ?>
                                    <tr>
                                        <td class="fw-bold">#ORD-<?= htmlspecialchars($order['id']); ?></td>
                                        <td>
                                            <div class="user-meta">
                                             
                                                <div class="user-details">
                                                    <h6><?= htmlspecialchars($order['firstname'] . ' ' . $order['lastname']); ?></h6>
                                                    <span><?= htmlspecialchars($order['email']); ?></span>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div>
                                                <span class="stock-symbol"><?= htmlspecialchars($order['symbol']); ?></span>
                                                <div class="small text-muted mt-1"><?= htmlspecialchars($order['stock_name']); ?></div>
                                            </div>
                                        </td>
                                        <td class="fw-bold"><?= htmlspecialchars($order['quantity']); ?></td>
                                        <td class="price-text">$<?= number_format($order['price'], 2); ?></td>
                                        <td class="price-text text-primary fw-bold">$<?= number_format($order['total_cost'], 2); ?></td>
                                        <td>
                                            <div class="small text-muted">
                                                <i class="bi bi-calendar me-1"></i><?= date('M d, Y', strtotime($order['date'])); ?><br>
                                                <i class="bi bi-clock me-1"></i><?= date('h:i A', strtotime($order['date'])); ?>
                                            </div>
                                        </td>
                                        <td><span class="badge <?= $badge_class ?>"><?= htmlspecialchars($order['status']); ?></span></td>
                                       
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="9" class="text-center py-5 text-muted">
                                            <i class="bi bi-inbox fs-1 d-block mb-2 opacity-50"></i>
                                            No stock orders found.
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <div class="card-footer bg-white border-top-0 py-3">
                    <nav aria-label="Page navigation">
                        <ul class="pagination justify-content-center mb-0">
                            <li class="page-item <?= ($current_page <= 1) ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?page=<?= max(1, $current_page - 1); ?>">Previous</a>
                            </li>
                            <?php for ($p = 1; $p <= $total_pages; $p++): ?>
                                <li class="page-item <?= ($p == $current_page) ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?= $p; ?>"><?= $p; ?></a>
                                </li>
                            <?php endfor; ?>
                            <li class="page-item <?= ($current_page >= $total_pages) ? 'disabled' : ''; ?>">
                                <a class="page-link" href="?page=<?= min($total_pages, $current_page + 1); ?>">Next</a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>

        </div>
    </div>
</main>

<script src="assets/vendor/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/vendor/overlay-scrollbar/js/overlayscrollbars.min.js"></script>
<script src="assets/vendor/apexcharts/js/apexcharts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script src="assets/js/functions.js"></script>

</body>
</html>