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

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

function e($v){ return htmlspecialchars($v ?? '', ENT_QUOTES); }

/* SEARCH */
$q = trim($_GET['q'] ?? '');

$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 20;
$offset = ($page - 1) * $per_page;

$isMR = ($_SESSION['role'] === 'medical_representative');
$mrId = (int)($_SESSION['user_id']);

$unionSql = "
    SELECT
        l.id,
        p.product_name,
        l.type,
        l.qty,
        l.created_at,
        l.remarks
    FROM stock_ledger l
    LEFT JOIN products p ON p.id = l.product_id

    UNION ALL

    SELECT
        p.id,
        p.product_name,
        'IN' AS type,
        p.qty,
        p.created_at,
        'Approved Product' AS remarks
    FROM products p
    WHERE p.status = 'approved'

    UNION ALL

    SELECT
        bi.id,
        COALESCE(p2.product_name, bi.product_name, 'Unknown Product') AS product_name,
        'OUT' AS type,
        bi.qty,
        b.created_at,
        CONCAT('Product Sold - Bill #', b.id) AS remarks
    FROM bill_items bi
    JOIN bills b ON b.id = bi.bill_id
    LEFT JOIN products p2 ON p2.id = bi.product_id
    " . ($isMR ? "WHERE b.mr_id = ?" : "") . "
";

/* ================= COUNT ================= */
$sql_count = "SELECT COUNT(*) as total FROM ($unionSql) temp";
$countParams = [];
$countTypes  = "";

if ($isMR) {
    $countParams[] = $mrId;
    $countTypes .= "i";
}

if ($q !== '') {
    $sql_count .= " WHERE product_name LIKE ? OR type LIKE ? OR remarks LIKE ?";
    $like = "%$q%";
    $countParams[] = $like;
    $countParams[] = $like;
    $countParams[] = $like;
    $countTypes .= "sss";
}

$stmt = $conn->prepare($sql_count);
if ($countTypes !== '') {
    $stmt->bind_param($countTypes, ...$countParams);
}
$stmt->execute();
$total = $stmt->get_result()->fetch_assoc()['total'] ?? 0;
$stmt->close();

/* ================= DATA ================= */
$sql = "SELECT * FROM ($unionSql) final";
$dataParams = [];
$dataTypes  = "";

if ($q !== '') {
    $sql .= " WHERE product_name LIKE ? OR type LIKE ? OR remarks LIKE ?";
    $like = "%$q%";
    $dataParams[] = $like;
    $dataParams[] = $like;
    $dataParams[] = $like;
    $dataTypes .= "sss";
}

$sql .= " ORDER BY created_at DESC LIMIT ? OFFSET ?";

if ($isMR) {
    $dataParams = array_merge([$mrId], $dataParams);
    $dataTypes = "i" . $dataTypes;
}

$dataParams[] = $per_page;
$dataParams[] = $offset;
$dataTypes .= "ii";

$stmt = $conn->prepare($sql);
$stmt->bind_param($dataTypes, ...$dataParams);
$stmt->execute();

$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$total_pages = ceil($total / $per_page);
?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Stock Ledger</title>

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

<style>
body{
    font-family:Inter, Arial;
    background:#f4f7fb;
    margin:0;
}

/* LAYOUT */
.container{
    margin-left:260px;
    padding:40px 20px 20px;
}

/* CARD */
.card{
    background:#fff;
    padding:16px;
    border-radius:14px;
    box-shadow:0 8px 24px rgba(2,6,23,.08);
    border:1px solid #e2e8f0;
}

/* TITLE */
.title{
    display:flex;
    align-items:center;
    gap:8px;
    font-size:22px;
    font-weight:700;
    margin-bottom:12px;
    color:#0f172a;
}

.title i{
    color:#334155;
    font-size:18px;
}

/* SEARCH */
.search-box input{
    width:100%;
    padding:10px 12px;
    border-radius:10px;
    border:1px solid #e2e8f0;
    margin-bottom:14px;
    font-size:13px;
}

/* TABLE */
.table{
    width:100%;
    border-spacing:0 8px;
}

.table th{
    background:#334155;
    color:#fff;
    padding:10px;
    font-size:13px;
}

.table td{
    background:#fff;
    padding:10px;
    border-top:1px solid #eee;
    border-bottom:1px solid #eee;
    font-size:13px;
}

/* ROUNDED ROW */
.table tr td:first-child{
    border-left:1px solid #eee;
    border-radius:10px 0 0 10px;
}
.table tr td:last-child{
    border-right:1px solid #eee;
    border-radius:0 10px 10px 0;
}

.table tr:hover td{
    background:#f8fafc;
}

/* BADGE */
.badge{
    padding:5px 10px;
    border-radius:999px;
    font-size:11px;
    font-weight:700;
}

/* COLORS */
.in{
    
    color:#16a34a;
}

.out{
    
    color:#dc2626;
}

/* PAGINATION */
.pagination{
    margin-top:14px;
    display:flex;
    gap:6px;
    flex-wrap:wrap;
}

.pagination a{
    padding:6px 10px;
    font-size:12px;
    border-radius:8px;
    text-decoration:none;
    background:#334155;
    color:#fff;
    font-weight:600;
}

.pagination a:hover{
    background:#374155;
}

/* RESPONSIVE */
@media(max-width:992px){
    .container{margin-left:0;}
}

/* ================= MOBILE RESPONSIVE (LEDGER CARD UI) ================= */
@media (max-width: 768px){

    .container{
        margin-left:0 !important;
        padding:12px;
        width:100%;
    }

    .card{
        padding:14px;
    }

    .title{
        font-size:18px;
    }

    /* SEARCH */
    .search-box input{
        font-size:13px;
    }

    /* ❌ HIDE TABLE HEADER */
    .table thead{
        display:none;
    }

    /* ✅ CARD STYLE */
    .table tbody tr{
        display:block;
        margin-bottom:12px;
        border:1px solid #e2e8f0;
        border-radius:12px;
        padding:10px;
        background:#f8fafc;
    }

    /* EACH ROW FIELD */
    .table tbody td{
        display:flex;
        justify-content:space-between;
        padding:6px 0;
        border:none;
        font-size:12px;
    }

    /* LABEL */
    .table tbody td::before{
        content:attr(data-label);
        font-weight:600;
        color:#64748b;
    }

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

    /* PAGINATION */
    .pagination{
        justify-content:center;
    }

    .pagination a{
        font-size:11px;
        padding:6px 10px;
    }
}
</style>
</head>

<body>

<?php include 'salesexecutivesidebar.php'; ?>
<?php include '../header.php'; ?>

<div class="container">
<div class="card">

<div class="title" style="color: #000;">
    <i class="fa fa-boxes-stacked"></i>
    Stock Ledger
</div>

<form method="get" class="search-box">
<input type="search" name="q" placeholder="Search product..." value="<?php echo e($q); ?>">
</form>

<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Product</th>
<th>Type</th>
<th>Qty</th>
<th>Date</th>
<th>Remarks</th>
</tr>
</thead>

<tbody>
<?php foreach($rows as $r): ?>
<tr>

<td data-label="ID"><?php echo $r['id']; ?></td>

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

<td data-label="Type">
<span class="badge <?php echo strtolower($r['type']); ?>">
<?php echo $r['type']; ?>
</span>
</td>

<td data-label="Qty"><?php echo $r['qty']; ?></td>

<td data-label="Date"><?php echo $r['created_at']; ?></td>

<td data-label="Remarks"><?php echo e($r['remarks']); ?></td>

</tr>
<?php endforeach; ?>
</tbody>
</table>

<div class="pagination">
<?php for($i=1;$i<=$total_pages;$i++): ?>
<a href="?page=<?php echo $i; ?>&q=<?php echo urlencode($q); ?>">
<?php echo $i; ?>
</a>
<?php endfor; ?>
</div>

</div>
</div>

</body>
</html>