<?php
include 'auth_check.php';

if (!isAdmin() && !(isset($_GET['ajax']) && $_GET['ajax'] == 1)) {
    header("Location: sale.php");
    exit();
}

$today = date('Y-m-d');
$nextMonth = date('Y-m-d', strtotime('+1 month'));
$pageError = '';

try {
    if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
        header('Content-Type: text/html; charset=UTF-8');

        $keyword = trim($_GET['keyword'] ?? '');
        if ($keyword === '') {
            exit();
        }

        $searchLike = '%' . $keyword . '%';
        $stmt = $conn->prepare("SELECT product_name, selling_price, unit, is_dual_mode, dual_mode_name_1, dual_mode_qty_1, dual_mode_price_1, dual_mode_name_2, dual_mode_qty_2, dual_mode_price_2 FROM stock WHERE product_name LIKE ? ORDER BY product_name ASC LIMIT 10");
        $stmt->bind_param("s", $searchLike);
        $stmt->execute();
        $result = $stmt->get_result();

        while ($row = $result->fetch_assoc()) {
            $isDual = (int)($row['is_dual_mode'] ?? 0) === 1;

            $displayText = $row['product_name'] . " - " . $row['unit'];
            if ($isDual) {
                $displayText .= " - " . ($row['dual_mode_name_1'] ?? 'Mode 1') . ": Rs." . number_format((float)($row['dual_mode_price_1'] ?? 0), 2);
                $displayText .= " | " . ($row['dual_mode_name_2'] ?? 'Mode 2') . ": Rs." . number_format((float)($row['dual_mode_price_2'] ?? 0), 2);
            } else {
                $displayText .= " - Rs." . number_format((float)$row['selling_price'], 2);
            }

            echo '<div class="suggestion-item" '
                . 'onclick="selectProductForSale(this)" '
                . 'data-product_name="' . htmlspecialchars($row['product_name'], ENT_QUOTES) . '" '
                . 'data-standard_price="' . htmlspecialchars($row['selling_price'], ENT_QUOTES) . '" '
                . 'data-unit="' . htmlspecialchars($row['unit'], ENT_QUOTES) . '" '
                . 'data-is_dual_mode="' . (int)($row['is_dual_mode'] ?? 0) . '" '
                . 'data-dual_mode_name_1="' . htmlspecialchars($row['dual_mode_name_1'] ?? '', ENT_QUOTES) . '" '
                . 'data-dual_mode_qty_1="' . htmlspecialchars($row['dual_mode_qty_1'] ?? '', ENT_QUOTES) . '" '
                . 'data-dual_mode_price_1="' . htmlspecialchars($row['dual_mode_price_1'] ?? '', ENT_QUOTES) . '" '
                . 'data-dual_mode_name_2="' . htmlspecialchars($row['dual_mode_name_2'] ?? '', ENT_QUOTES) . '" '
                . 'data-dual_mode_qty_2="' . htmlspecialchars($row['dual_mode_qty_2'] ?? '', ENT_QUOTES) . '" '
                . 'data-dual_mode_price_2="' . htmlspecialchars($row['dual_mode_price_2'] ?? '', ENT_QUOTES) . '"'
                . '>'
                . htmlspecialchars($displayText)
                . '</div>';
        }
        exit();
    }

    $search = trim($_GET['search'] ?? '');
    $searchLike = '%' . $search . '%';
    $stockStmt = $conn->prepare("SELECT product_name, purchasing_price, selling_price, purchased_qty, unit, invoice_number, expiry_date, is_dual_mode, dual_mode_name_1, dual_mode_qty_1, dual_mode_price_1, dual_mode_name_2, dual_mode_qty_2, dual_mode_price_2 FROM stock WHERE product_name LIKE ? ORDER BY purchased_qty ASC, product_name ASC");
    $stockStmt->bind_param("s", $searchLike);
    $stockStmt->execute();
    $stock = $stockStmt->get_result();

    $purchase_search = trim($_GET['purchase_search'] ?? '');
    $purchaseLike = '%' . $purchase_search . '%';
    $purchaseStmt = $conn->prepare("SELECT product_name, purchasing_price, selling_price, purchased_qty, unit, invoice_number, expiry_date, total_purchasing_price, entered_date, entered_time, entered_user, is_dual_mode, dual_mode_name_1, dual_mode_qty_1, dual_mode_price_1, dual_mode_name_2, dual_mode_qty_2, dual_mode_price_2 FROM all_purchasing_product_data WHERE product_name LIKE ? ORDER BY id DESC");
    $purchaseStmt->bind_param("s", $purchaseLike);
    $purchaseStmt->execute();
    $purchaseData = $purchaseStmt->get_result();

    $return_search = trim($_GET['return_search'] ?? '');
    $returnLike = '%' . $return_search . '%';
    $returnStmt = $conn->prepare("SELECT * FROM returned_product_data WHERE product_name LIKE ? OR bill_number LIKE ? ORDER BY id DESC");
    $returnStmt->bind_param("ss", $returnLike, $returnLike);
    $returnStmt->execute();
    $returnData = $returnStmt->get_result();
} catch (Throwable $e) {
    app_log_error('stock.php error: ' . $e->getMessage());
    if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
        http_response_code(503);
        exit('<div class="suggestion-item">Connection issue. Please try again.</div>');
    }
    $pageError = 'Data could not be loaded at the moment. Please try again.';
    $stock = [];
    $purchaseData = [];
    $returnData = [];
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Krushi Sewa Piyasa-Stock</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="layout">
    <?php renderSidebar('stock'); ?>
    <main class="main-content">
        <div class="topbar"><span class="topbar-left-status"></span>Logged User: <?php echo $_SESSION['name']; ?> | <?php echo $_SESSION['user_category']; ?></div>

        <?php if ($pageError !== '') { ?>
            <div class="message-box error-box"><?php echo htmlspecialchars($pageError); ?></div>
        <?php } ?>

        <div class="table-card">
            <h2>Stock Checking</h2>
            <form method="GET" class="search-bar">
                <input type="text" name="search" placeholder="Search Product Name" value="<?php echo htmlspecialchars($search); ?>">
                <button type="submit">Search</button>
                <a href="export_stock.php?type=stock" class="export-btn">Export Excel</a>
            </form>

            <div class="table-scroll">
                <table>
                    <tr>
                        <th>Product</th>
                        <th>Purchase Value</th>
                        <th>Standard / Primary Price</th>
                        <th>Mode 1</th>
                        <th>Mode 2</th>
                        <th>Total Qty</th>
                        <th>Unit</th>
                        <th>Invoice No</th>
                        <th>Expiry Date</th>
                        <th>Status</th>
                    </tr>
                    <?php foreach ($stock as $row) {
                        $low = (float)$row['purchased_qty'] <= 5;
                        $nearExpiry = !empty($row['expiry_date']) && $row['expiry_date'] >= $today && $row['expiry_date'] <= $nextMonth;
                        $rowClass = '';
                        if ($low) $rowClass = 'low-stock';
                        if ($nearExpiry) $rowClass .= ($rowClass ? ' ' : '') . 'near-expiry';
                        $isDual = (int)($row['is_dual_mode'] ?? 0) === 1;
                    ?>
                    <tr class="<?php echo $rowClass; ?>">
                        <td><?php echo htmlspecialchars($row['product_name']); ?></td>
                        <td><?php echo number_format((float)$row['purchasing_price'],2); ?></td>
                        <td><?php echo number_format((float)$row['selling_price'],2); ?></td>
                        <td>
                            <?php
                            if ($isDual) {
                                echo htmlspecialchars($row['dual_mode_name_1']) . ' - Rs.' . number_format((float)$row['dual_mode_price_1'], 2)
                                   . ' (' . number_format((float)$row['dual_mode_qty_1'], 2) . ' ' . htmlspecialchars($row['unit']) . ')';
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                        <td>
                            <?php
                            if ($isDual) {
                                echo htmlspecialchars($row['dual_mode_name_2']) . ' - Rs.' . number_format((float)$row['dual_mode_price_2'], 2)
                                   . ' (' . number_format((float)$row['dual_mode_qty_2'], 2) . ' ' . htmlspecialchars($row['unit']) . ')';
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                        <td><?php echo number_format((float)$row['purchased_qty'],2); ?></td>
                        <td><?php echo htmlspecialchars($row['unit']); ?></td>
                        <td><?php echo htmlspecialchars($row['invoice_number']); ?></td>
                        <td><?php echo htmlspecialchars($row['expiry_date']); ?></td>
                        <td>
                            <?php
                            if ($nearExpiry) {
                                echo 'Expiring Soon';
                            } else {
                                echo $low ? 'Low Quantity' : 'Available';
                            }
                            ?>
                        </td>
                    </tr>
                    <?php } ?>
                </table>
            </div>
        </div>

        <div class="table-card">
            <h2>All Purchasing Product Data</h2>
            <form method="GET" class="search-bar">
                <input type="text" name="purchase_search" placeholder="Search Product Name" value="<?php echo htmlspecialchars($purchase_search); ?>">
                <button type="submit">Search</button>
                <a href="export_stock.php?type=purchasing" class="export-btn">Export Excel</a>
            </form>

            <div class="table-scroll">
                <table>
                    <tr>
                        <th>Product</th>
                        <th>Purchase Value</th>
                        <th>Primary Price</th>
                        <th>Mode 1</th>
                        <th>Mode 2</th>
                        <th>Purchased Qty</th>
                        <th>Unit</th>
                        <th>Invoice No</th>
                        <th>Expiry Date</th>
                        <th>Total Purchasing Price</th>
                        <th>Date</th>
                        <th>Time</th>
                        <th>User</th>
                    </tr>
                    <?php foreach ($purchaseData as $row) { ?>
                    <tr>
                        <td><?php echo htmlspecialchars($row['product_name']); ?></td>
                        <td><?php echo number_format((float)$row['purchasing_price'],2); ?></td>
                        <td><?php echo number_format((float)$row['selling_price'],2); ?></td>
                        <td>
                            <?php
                            if ((int)($row['is_dual_mode'] ?? 0) === 1) {
                                echo htmlspecialchars($row['dual_mode_name_1']) . ' - Rs.' . number_format((float)$row['dual_mode_price_1'],2)
                                   . ' (' . number_format((float)$row['dual_mode_qty_1'],2) . ' ' . htmlspecialchars($row['unit']) . ')';
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                        <td>
                            <?php
                            if ((int)($row['is_dual_mode'] ?? 0) === 1) {
                                echo htmlspecialchars($row['dual_mode_name_2']) . ' - Rs.' . number_format((float)$row['dual_mode_price_2'],2)
                                   . ' (' . number_format((float)$row['dual_mode_qty_2'],2) . ' ' . htmlspecialchars($row['unit']) . ')';
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                        <td><?php echo number_format((float)$row['purchased_qty'],2); ?></td>
                        <td><?php echo htmlspecialchars($row['unit']); ?></td>
                        <td><?php echo htmlspecialchars($row['invoice_number']); ?></td>
                        <td><?php echo htmlspecialchars($row['expiry_date']); ?></td>
                        <td><?php echo number_format((float)$row['total_purchasing_price'],2); ?></td>
                        <td><?php echo htmlspecialchars($row['entered_date']); ?></td>
                        <td><?php echo htmlspecialchars($row['entered_time']); ?></td>
                        <td><?php echo htmlspecialchars($row['entered_user']); ?></td>
                    </tr>
                    <?php } ?>
                </table>
            </div>
        </div>

        <div class="table-card">
            <h2>Returned Product Data</h2>
            <form method="GET" class="search-bar">
                <input type="text" name="return_search" placeholder="Search Product / Bill Number" value="<?php echo htmlspecialchars($return_search); ?>">
                <button type="submit">Search</button>
            </form>

            <div class="table-scroll">
                <table>
                    <tr>
                        <th>Bill Number</th>
                        <th>Product</th>
                        <th>Returned Qty</th>
                        <th>Unit</th>
                        <th>Returned Date</th>
                        <th>Returned Time</th>
                        <th>User</th>
                    </tr>
                    <?php foreach ($returnData as $row) { ?>
                    <tr>
                        <td><?php echo htmlspecialchars($row['bill_number']); ?></td>
                        <td><?php echo htmlspecialchars($row['product_name']); ?></td>
                        <td><?php echo number_format((float)$row['returned_qty'], 2); ?></td>
                        <td><?php echo htmlspecialchars($row['unit']); ?></td>
                        <td><?php echo htmlspecialchars($row['returned_date']); ?></td>
                        <td><?php echo htmlspecialchars($row['returned_time']); ?></td>
                        <td><?php echo htmlspecialchars($row['entered_user']); ?></td>
                    </tr>
                    <?php } ?>
                </table>
            </div>
        </div>
    </main>
</div>
</body>
</html>
