<?php
session_start();
require_once '../config.php';

/* ================= EXPORT TO EXCEL (SAMPLE LOW STOCK) ================= */
if (isset($_GET['export']) && $_GET['export'] == 1) {

    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=sample_low_stock.xls");

    echo "SR\tProduct Name\tGeneric Name\tBrand Name\tPacket Qty\tUnits/Packet\n";

    $sr = 1;

    /* ✅ USER COUNTRY */
    $userId = (int)$_SESSION['user_id'];

    $stmt = $conn->prepare("SELECT country FROM users WHERE id=? LIMIT 1");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    $agencyCountryName = trim($user['country'] ?? '');

    /* ✅ STOCK LIMIT */
    $stmt = $conn->prepare("SELECT limit_qty FROM stock_limit_settings WHERE setting_key='sample_stock' LIMIT 1");
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();

    $limit = isset($row['limit_qty']) && $row['limit_qty'] > 0 
        ? (int)$row['limit_qty'] 
        : 50;

    /* ✅ SAME DATA AS TABLE */
    $stmt = $conn->prepare("
        SELECT product_name, generic_name, brand_name, packet_qty, units_packet
        FROM sample_products
        WHERE country = ?
          AND packet_qty <= ?
        ORDER BY packet_qty ASC
    ");

    $stmt->bind_param("si", $agencyCountryName, $limit);
    $stmt->execute();

    $res = $stmt->get_result();

    while ($row = $res->fetch_assoc()) {
        echo $sr++ . "\t" .
             ($row['product_name'] ?? '-') . "\t" .
             ($row['generic_name'] ?? '-') . "\t" .
             ($row['brand_name'] ?? '-') . "\t" .
             ($row['packet_qty'] ?? 0) . "\t" .
             ($row['units_packet'] ?? '-') . "\n";
    }

    exit;
}
$role = strtolower($_SESSION['role'] ?? '');

if (!isset($_SESSION['user_id']) || !in_array($role, ['sales_manager'])) {
    header('Location: ../login.php');
    exit;
}

function e($v) {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

/* =========================================================
   GET AGENCY COUNTRY
========================================================= */
$userId = (int)$_SESSION['user_id'];
$agencyCountryName = '';

$stmt = $conn->prepare("SELECT country FROM users WHERE id = ? LIMIT 1");
if ($stmt) {
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($row = $res->fetch_assoc()) {
        $agencyCountryName = trim($row['country'] ?? '');
    }
}

/* =========================================================
   STOCK LIMIT
========================================================= */
$settingKey = 'sample_stock';
$currentLimit = null;

$stmt = $conn->prepare("SELECT limit_qty FROM stock_limit_settings WHERE setting_key = ? LIMIT 1");
if ($stmt) {
    $stmt->bind_param("s", $settingKey);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($row = $res->fetch_assoc()) {
        $currentLimit = (int)$row['limit_qty'];
    }
}

/* =========================================================
   FETCH SAMPLE PRODUCTS
========================================================= */
$sample_products = [];
$totalLowStock = 0;

if (!empty($agencyCountryName)) {

    if ($currentLimit !== null) {
        $stmt = $conn->prepare("
            SELECT *
            FROM sample_products
            WHERE country = ?
              AND packet_qty <= ?
            ORDER BY packet_qty ASC
        ");
        if ($stmt) {
            $stmt->bind_param("si", $agencyCountryName, $currentLimit);
        }
    } else {
        $stmt = $conn->prepare("
            SELECT *
            FROM sample_products
            WHERE country = ?
            ORDER BY packet_qty ASC
        ");
        if ($stmt) {
            $stmt->bind_param("s", $agencyCountryName);
        }
    }

    if ($stmt) {
        $stmt->execute();
        $res = $stmt->get_result();

        while ($row = $res->fetch_assoc()) {
            $sample_products[] = $row;
        }

        $totalLowStock = count($sample_products);
    }
}

/* =========================================================
   MESSAGES
========================================================= */
$msg = '';
$err = '';

if (isset($_GET['msg']) && $_GET['msg'] === 'saved') {
    $msg = "Stock limit saved successfully.";
}
if (isset($_GET['msg']) && $_GET['msg'] === 'deleted') {
    $msg = "Stock limit deleted successfully.";
}

$current = basename($_SERVER['PHP_SELF']);
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Sample Stock</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">

    <style>
        :root{
            --bg:#eef3f9;
            --card:#ffffff;
            --text:#0f172a;
            --muted:#64748b;
            --border:#dfe7f1;
            --shadow:0 16px 35px rgba(15, 23, 42, 0.08);
            --shadow-soft:0 10px 24px rgba(15, 23, 42, 0.06);
            --radius:18px;

            --primary:#374155;
            --primary-2:#273142;
            --primary-soft:#eef2f7;

            --low-bg:#fef3c7;
            --low-text:#92400e;

            --ok-bg:#dcfce7;
            --ok-text:#166534;
        }

        *{
            box-sizing:border-box;
        }

        body{
            margin:0;
            font-family: Inter, Arial, Helvetica, sans-serif;
            background:var(--bg);
            color:var(--text);
        }

        a{
            text-decoration:none;
            color:inherit;
        }

        .wrapper{
            margin-left:250px;
            margin-top:20px;
            min-height:calc(100vh - 20px);
        }

        .content{
            padding:14px 16px 16px;
            max-width:1600px;
        }

        .page-title{
            background:transparent;
            border:none;
            box-shadow:none;
            padding:10px 0;
            margin-bottom:10px;
        }

        .page-title h1{
            margin:0;
            font-size:22px;
            color:#0b1b3a;
            font-weight:700;
            letter-spacing:.2px;
            display:flex;
            align-items:center;
            gap:12px;
        }

        .page-title h1 i{
            background:#eef2f7;
            color:#374155;
            width:36px;
            height:36px;
            display:flex;
            align-items:center;
            justify-content:center;
            border-radius:14px;
            font-size:14px;
        }

        .page-title p{
            margin:6px 0 0;
            color:#64748b;
            font-size:13px;
            line-height:1.5;
        }

        .stats{
            display:grid;
            grid-template-columns:repeat(3, minmax(0, 1fr));
            gap:12px;
            margin-bottom:14px;
        }

        .stat-card{
            background:linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
            border:1px solid var(--border);
            border-radius:18px;
            box-shadow:var(--shadow-soft);
            padding:12px;
            position:relative;
            overflow:hidden;
            min-height:90px;
        }

        .stat-card::before{
            content:'';
            position:absolute;
            inset:0 auto auto 0;
            width:100%;
            height:4px;
            background:linear-gradient(90deg, #374155, #6b7280);
        }

        .stat-card .label{
            color:var(--muted);
            font-size:10px;
            margin-bottom:4px;
            font-weight:800;
            text-transform:uppercase;
            letter-spacing:.04em;
        }

        .stat-card .value{
            font-size:18px;
            font-weight:900;
            color:#0f172a;
            line-height:1.1;
            word-break:break-word;
        }

        .stat-card .sub{
            margin-top:6px;
            color:var(--muted);
            font-size:11px;
            line-height:1.4;
        }

        .card{
            background:var(--card);
            border:1px solid var(--border);
            border-radius:18px;
            box-shadow:var(--shadow);
            overflow:hidden;
        }

        .card-head{
            padding:12px 16px;
            border-bottom:1px solid var(--border);
            display:flex;
            align-items:center;
            justify-content:space-between;
            gap:10px;
            background:linear-gradient(180deg, #ffffff, #f8fbff);
        }

        .card-head h2{
            margin:0;
            font-size:16px;
            color:#0f172a;
            font-weight:900;
            display:flex;
            align-items:center;
            gap:10px;
        }

        .table-wrap{
            overflow-x:auto;
            width:100%;
        }

        table{
            width:100%;
            border-collapse:separate;
            border-spacing:0;
            table-layout:auto;
            min-width:100%;
        }

        colgroup col:nth-child(1){ width:6%; }
        colgroup col:nth-child(2){ width:28%; }
        colgroup col:nth-child(3){ width:25%; }
        colgroup col:nth-child(4){ width:18%; }
        colgroup col:nth-child(5){ width:11%; }
        colgroup col:nth-child(6){ width:12%; }

        thead th{
            position:sticky;
            top:0;
            z-index:1;
            background:#374155;
            color:#fff;
            font-size:13px;
            text-transform:uppercase;
            letter-spacing:.05em;
            font-weight:900;
            padding:10px;
            border-bottom:1px solid #e2e8f0;
            white-space:nowrap;
        }

        tbody td{
            padding:10px;
            border-bottom:1px solid #edf2f7;
            font-size:13px;
            color:#374155;
            vertical-align:middle;
            white-space:nowrap;
            overflow:hidden;
            text-overflow:ellipsis;
        }

        tbody tr:nth-child(even){
            background:#fcfdff;
        }

        tbody tr:hover{
            background:#f7fbff;
        }

        th.center, td.center{ text-align:center; }
        th.right, td.right{ text-align:right; }
        th.left, td.left{ text-align:left; }

        td.sr{
            text-align:center;
            font-weight:700;
            color:#475569;
        }

        .badge{
            display:inline-flex;
            align-items:center;
            justify-content:center;
            min-width:54px;
            padding:5px 10px;
            border-radius:999px;
            font-size:11px;
            font-weight:800;
            line-height:1;
            box-shadow:inset 0 0 0 1px rgba(0,0,0,.03);
        }

        .badge-low{
            background:var(--low-bg);
            color:var(--low-text);
        }

        .badge-ok{
            background:var(--ok-bg);
            color:var(--ok-text);
        }

        .empty{
            padding:42px 18px;
            text-align:center;
            color:var(--muted);
        }

        .empty i{
            font-size:42px;
            margin-bottom:12px;
            display:block;
            color:#94a3b8;
        }

        .alert{
            padding:13px 14px;
            border-radius:14px;
            margin-bottom:16px;
            font-weight:700;
            border:1px solid transparent;
        }

        .alert.success{
            background:#ecfdf5;
            color:#166534;
            border-color:#bbf7d0;
        }

        .alert.error{
            background:#fef2f2;
            color:#991b1b;
            border-color:#fecaca;
        }

        @media (max-width: 1100px){
            .stats{
                grid-template-columns:1fr;
            }

            .wrapper{
                margin-left:0;
                margin-top:20px;
            }
        }

      /* ================= MOBILE PRO VIEW ================= */
@media (max-width: 768px){

    html, body{
        overflow-x: hidden;
    }

    .wrapper{
        margin-left: 0 !important;
    }

    .content{
        padding: 12px;
    }

    /* TITLE */
    .page-title h1{
        font-size: 18px;
    }

    .page-title p{
        font-size: 12px;
    }

    /* STATS */
    .stats{
        grid-template-columns: 1fr;
    }

    /* ❌ REMOVE TABLE SCROLL */
    .table-wrap{
        overflow: visible;
    }

    table, thead, tbody, tr, td{
        display: block;
        width: 100%;
    }

    thead{
        display: none;
    }

    /* CARD STYLE */
    tbody tr{
        background: #ffffff;
        margin-bottom: 12px;
        padding: 12px;
        border-radius: 16px;
        box-shadow: 0 6px 18px rgba(0,0,0,0.06);
        border: 1px solid #e5e7eb;
    }

    /* ROW DATA */
    tbody td{
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px 0;
        font-size: 13px;
        border: none;
    }

    /* LABELS */
    tbody td::before{
        content: attr(data-label);
        font-weight: 700;
        color: #64748b;
        font-size: 11px;
        text-transform: uppercase;
    }

    /* SR FIX */
    td.sr{
        justify-content: center;
        font-weight: 900;
        font-size: 14px;
        border-bottom: 1px dashed #e5e7eb;
        margin-bottom: 6px;
    }

    /* BADGE */
    .badge{
        font-size: 11px;
        padding: 5px 10px;
    }

    .empty{
        padding: 30px 10px;
        font-size: 13px;
    }
}
.export-btn{
    display:inline-flex;
    align-items:center;
    gap:8px;
    background:linear-gradient(135deg,#3b82f6,#2563eb);
    color:#fff;
    padding:10px 18px;
    border-radius:12px;
    font-weight:600;
    text-decoration:none;
    font-size:14px;
    transition:all 0.3s ease;
    box-shadow:0 6px 15px rgba(37,99,235,0.3);
}

.export-btn:hover{
    transform:translateY(-2px);
    box-shadow:0 10px 20px rgba(37,99,235,0.4);
}
    </style>
</head>
<body>

<?php
$header = __DIR__ . '/../header.php';
if (file_exists($header)) {
    include $header;
}
?>

<?php
$salesManagerSidebar = __DIR__ . '/salesmanagersidebar.php';
if (file_exists($salesManagerSidebar)) {
    include $salesManagerSidebar;
}
?>

<div class="wrapper">
    <div class="content">
        <div class="page-title" style="display:flex;justify-content:space-between;align-items:center;">

    <div>
        <h1>
            <i class="fa-solid fa-boxes-stacked"></i>
            Sample Stock
        </h1>
        <p>Low stock products are shown based on your agency country and stock limit.</p>
    </div>

    <a href="?export=1" class="export-btn">
        <i class="fa fa-file-excel"></i> Export Excel
    </a>

</div>

        <?php if ($msg !== ''): ?>
            <div class="alert success"><?php echo e($msg); ?></div>
        <?php endif; ?>

        <?php if ($err !== ''): ?>
            <div class="alert error"><?php echo e($err); ?></div>
        <?php endif; ?>

        <div class="stats">
            <div class="stat-card">
                <div class="label">Current Commercial Stock Limit</div>
                <div class="value"><?php echo $currentLimit !== null ? e($currentLimit) : 'Not Set'; ?></div>
                <div class="sub">Set by RA/Admin</div>
            </div>

            <div class="stat-card">
                <div class="label">Agency Country</div>
                <div class="value"><?php echo e($agencyCountryName ?: 'Not Found'); ?></div>
                <div class="sub">Products are matched only to this country</div>
            </div>

            <div class="stat-card">
                <div class="label">Low Stock Products</div>
                <div class="value"><?php echo e($totalLowStock); ?></div>
                <div class="sub">Items with qty less than or equal to the current limit</div>
            </div>
        </div>

        <div class="card">
            <div class="card-head">
                <h2>
                    <i class="fa-solid fa-triangle-exclamation" style="color:#000;"></i>
                    Low Stock Products
                </h2>
            </div>

            <div class="table-wrap">
                <?php if ($agencyCountryName === ''): ?>
                    <div class="empty">
                        <i class="fa-solid fa-map-location-dot"></i>
                        Agency country not found.
                    </div>
                <?php elseif (empty($sample_products)): ?>
                    <div class="empty">
                        <i class="fa-solid fa-box-open"></i>
                        No approved low stock products found for <?php echo e($agencyCountryName); ?>.
                    </div>
                <?php else: ?>
                    <table>
                        <colgroup>
                            <col>
                            <col>
                            <col>
                            <col>
                            <col>
                            <col>
                        </colgroup>
                        <thead>
                            <tr>
                                <th class="center">SR</th>
                                <th class="left">Product Name</th>
                                <th class="left">Generic Name</th>
                                <th class="left">Brand Name</th>
                                <th class="center">Packet Qty</th>
                                <th class="center">Units / Packet</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $sr = 1; foreach ($sample_products as $row): ?>
                               <tr>
    <td class="sr" data-label="SR"><?php echo $sr++; ?></td>

    <td data-label="Product">
        <?php echo e($row['product_name']); ?>
    </td>

    <td data-label="Generic">
        <?php echo e($row['generic_name']); ?>
    </td>

    <td data-label="Brand">
        <?php echo e($row['brand_name']); ?>
    </td>

    <td data-label="Packet Qty">
        <?php if ($currentLimit !== null && (int)$row['packet_qty'] <= $currentLimit): ?>
            <span class="badge badge-low"><?php echo e($row['packet_qty']); ?></span>
        <?php else: ?>
            <span class="badge badge-ok"><?php echo e($row['packet_qty']); ?></span>
        <?php endif; ?>
    </td>

    <td data-label="Units">
        <?php echo e($row['units_packet']); ?>
    </td>
</tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

</body>
</html>