<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

// ===================== QUICK STOCK UPDATE =====================
if(isset($_GET['quick_in'])){
    $id = intval($_GET['quick_in']);
    $conn->query("UPDATE assets SET quantity=quantity+1 WHERE id=$id");
    $conn->query("INSERT INTO asset_movements(asset_id,quantity,movement_type,reason,date) VALUES($id,1,'IN','Quick Add',NOW())");
    header("Location: assets.php");
    exit;
}
if(isset($_GET['quick_out'])){
    $id = intval($_GET['quick_out']);
    $qty = $conn->query("SELECT quantity FROM assets WHERE id=$id")->fetch_assoc()['quantity'];
    if($qty>0){
        $conn->query("UPDATE assets SET quantity=quantity-1 WHERE id=$id");
        $conn->query("INSERT INTO asset_movements(asset_id,quantity,movement_type,reason,date) VALUES($id,1,'OUT','Quick Remove',NOW())");
    }
    header("Location: assets.php");
    exit;
}

// ===================== ADD ASSET =====================
if(isset($_POST['add_asset'])){
    $name        = $conn->real_escape_string($_POST['name']);
    $section     = $conn->real_escape_string($_POST['section']);
    $quantity    = intval($_POST['quantity']);
    $unit_price  = floatval($_POST['unit_price']);

    $conn->query("INSERT INTO assets(name, section, quantity, unit_price, created_at)
                  VALUES('$name','$section',$quantity,$unit_price,NOW())");

    // Log initial movement
    $asset_id = $conn->insert_id;
    $conn->query("INSERT INTO asset_movements(asset_id, quantity, movement_type, reason, date)
                  VALUES($asset_id,$quantity,'IN','Initial stock',NOW())");

    echo "<script>alert('Asset added successfully!'); window.location='assets.php';</script>";
    exit;
}

// ===================== UPDATE MOVEMENT =====================
if(isset($_POST['asset_movement'])){
    $asset_id      = intval($_POST['asset_id']);
    $movement_type = $conn->real_escape_string($_POST['movement_type']); // IN or OUT
    $qty           = intval($_POST['quantity']);
    $reason        = $conn->real_escape_string($_POST['reason']);

    // Check stock if OUT
    if($movement_type=='OUT'){
        $current_qty = $conn->query("SELECT quantity FROM assets WHERE id=$asset_id")->fetch_assoc()['quantity'];
        if($qty > $current_qty){
            echo "<script>alert('Cannot remove more than available stock!'); window.location='assets.php';</script>";
            exit;
        }
        $conn->query("UPDATE assets SET quantity = quantity - $qty WHERE id=$asset_id");
    } else {
        $conn->query("UPDATE assets SET quantity = quantity + $qty WHERE id=$asset_id");
    }

    $conn->query("INSERT INTO asset_movements(asset_id, quantity, movement_type, reason, date)
                  VALUES($asset_id,$qty,'$movement_type','$reason',NOW())");

    echo "<script>alert('Movement recorded!'); window.location='assets.php';</script>";
    exit;
}

// ===================== FILTER / SEARCH =====================
$where = "1";
if(!empty($_GET['search_name'])) $where .= " AND name LIKE '%".$conn->real_escape_string($_GET['search_name'])."%'";
if(!empty($_GET['search_section'])) $where .= " AND section='".$conn->real_escape_string($_GET['search_section'])."'";
if(!empty($_GET['low_stock'])) $where .= " AND quantity<5";

$assets = $conn->query("SELECT * FROM assets WHERE $where ORDER BY section,name");

// Total assets value
$total_value = 0;
$section_totals = [];
while($a = $assets->fetch_assoc()){
    $val = $a['quantity'] * $a['unit_price'];
    $total_value += $val;
    $section_totals[$a['section']] = ($section_totals[$a['section']] ?? 0) + $val;
}

// Reset pointer
$assets->data_seek(0);

// Fetch sections for filter
$sections_arr = [];
$tmp = $conn->query("SELECT DISTINCT section FROM assets");
while($r = $tmp->fetch_assoc()) $sections_arr[] = $r['section'];

?>

<div class="container mt-4">
      <!-- ================= WELCOME MESSAGE ================= -->
   <?php $username = $_SESSION['username'] ?? 'Guest'; ?>
<div class="welcome-msg">
    <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
</div>

<h4>🏨Asset Management</h4>
<hr>

<!-- Filter -->
<form method="GET" class="row g-3 mb-3">
<div class="col-md-3">
<input type="text" name="search_name" placeholder="Asset Name" class="form-control" value="<?= $_GET['search_name'] ?? '' ?>">
</div>
<div class="col-md-3">
<select name="search_section" class="form-control">
    <option value="">All Sections</option>
    <?php foreach($sections_arr as $s): ?>
        <option value="<?= $s ?>" <?= (($_GET['search_section']??'')==$s)?'selected':'' ?>><?= $s ?></option>
    <?php endforeach; ?>
</select>
</div>
<div class="col-md-3">
<select name="low_stock" class="form-control">
    <option value="">Stock Status</option>
    <option value="1" <?= (($_GET['low_stock']??'')=='1')?'selected':'' ?>>Low Stock (&lt;5)</option>
</select>
</div>
<div class="col-md-3">
<button class="btn btn-primary w-100">Filter</button>
</div>
</form>

<!-- Add Asset -->
<div class="card mb-4">
<div class="card-header bg-success text-white">Add New Asset</div>
<div class="card-body">
<form method="POST" class="row g-3">
<div class="col-md-4">
<label>Asset Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="col-md-4">
<label>Section / Category</label>
<input type="text" name="section" class="form-control" required>
</div>
<div class="col-md-2">
<label>Quantity</label>
<input type="number" name="quantity" class="form-control" required>
</div>
<div class="col-md-2">
<label>Unit Price (MK)</label>
<input type="number" step="0.01" name="unit_price" class="form-control" required>
</div>
<div class="col-md-12 mt-3">
<button name="add_asset" class="btn btn-success w-100"><i class="fa fa-plus"></i> Add Asset</button>
</div>
</form>
</div>
</div>

<!-- Asset Summary -->
<div class="card mb-4">
<div class="card-header bg-primary text-white">Asset Summary</div>
<div class="card-body">
<p>Total Assets: <strong><?= $assets->num_rows ?></strong></p>
<p>Total Value: <strong>MK <?= number_format($total_value,2) ?></strong></p>
<hr>
<h6>Per Section:</h6>
<ul>
<?php foreach($section_totals as $sec=>$val): ?>
<li><?= htmlspecialchars($sec) ?>: MK <?= number_format($val,2) ?></li>
<?php endforeach; ?>
</ul>
</div>
</div>

<!-- Assets Table -->
<div class="card mb-4">
<div class="card-header bg-dark text-white">All Assets</div>
<div class="card-body">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Section</th>
<th>Qty</th>
<th>Unit Price</th>
<th>Total Value</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$i=1;
while($a = $assets->fetch_assoc()):
$total = $a['quantity']*$a['unit_price'];
?>
<tr>
<td><?= $i ?></td>
<td><?= htmlspecialchars($a['name']) ?></td>
<td><?= htmlspecialchars($a['section']) ?></td>
<td <?= $a['quantity']<5 ? "class='text-danger fw-bold'" : "" ?>><?= $a['quantity'] ?></td>
<td><?= number_format($a['unit_price'],2) ?></td>
<td><?= number_format($total,2) ?></td>
<td>
<button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#movementModal<?= $a['id'] ?>">Movement</button>
<a href="?quick_in=<?= $a['id'] ?>" class="btn btn-sm btn-success">+1</a>
<a href="?quick_out=<?= $a['id'] ?>" class="btn btn-sm btn-danger">-1</a>
</td>
</tr>

<!-- Movement Modal -->
<div class="modal fade" id="movementModal<?= $a['id'] ?>" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Asset Movement: <?= htmlspecialchars($a['name']) ?></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<form method="POST">
<input type="hidden" name="asset_id" value="<?= $a['id'] ?>">
<div class="mb-2">
<label>Movement Type</label>
<select name="movement_type" class="form-control" required>
<option value="IN">IN (Add Stock)</option>
<option value="OUT">OUT (Remove Stock)</option>
</select>
</div>
<div class="mb-2">
<label>Quantity</label>
<input type="number" name="quantity" class="form-control" required>
</div>
<div class="mb-2">
<label>Reason</label>
<input type="text" name="reason" class="form-control" required>
</div>
<div class="mt-2">
<button name="asset_movement" class="btn btn-success w-100">Submit Movement</button>
</div>
</form>
</div>
</div>
</div>
</div>

<?php $i++; endwhile; ?>
</tbody>
</table>
</div>
</div>

<!-- Movements History -->
<div class="card mb-4">
<div class="card-header bg-info text-white">Asset Movements History</div>
<div class="card-body">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>#</th>
<th>Asset</th>
<th>Quantity</th>
<th>Type</th>
<th>Reason</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php
$movements = $conn->query("
SELECT am.*, a.name as asset_name FROM asset_movements am 
LEFT JOIN assets a ON am.asset_id = a.id 
ORDER BY am.date DESC
");
$i=1;
while($m = $movements->fetch_assoc()):
?>
<tr>
<td><?= $i ?></td>
<td><?= htmlspecialchars($m['asset_name']) ?></td>
<td><?= $m['quantity'] ?></td>
<td><?= $m['movement_type'] ?></td>
<td><?= htmlspecialchars($m['reason']) ?></td>
<td><?= date("d-M-Y H:i", strtotime($m['date'])) ?></td>
</tr>
<?php $i++; endwhile; ?>
</tbody>
</table>
</div>
</div>

</div>

<?php include 'includes/footer.php'; ?>
