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

include 'config/db.php';

$message = "";
$low_stock_limit = 10;

/* ================= FILTERS ================= */
$search = trim($_GET['search'] ?? '');
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

/* ================= LOAD PRODUCT TYPES ================= */
$productTypes = $conn->query("SELECT DISTINCT product_type FROM vendor_products WHERE product_type<>'' ORDER BY product_type");

/* ================= LOAD PRODUCTS/VENDORS ================= */
$allProducts = [];
$q = $conn->query("
SELECT vp.*,v.vendor_name,v.vendor_phone,v.vendor_address,v.vendor_email,v.supply_type
FROM vendor_products vp
LEFT JOIN vendors v ON v.id=vp.vendor_id
ORDER BY vp.product_type, vp.brand_name
");

while($r=$q->fetch_assoc()){
    $allProducts[]=$r;
}

/* ================= RECEIVE PRODUCT ================= */
if(isset($_POST['receive'])){

    $vendor_id=(int)$_POST['vendor_id'];
    $product_type=trim($_POST['product_type']);
    $brand_name=trim($_POST['brand_name']);
    $quantity=(int)$_POST['quantity'];

    if($quantity<=0){
        $message="<div class='error'>Invalid quantity.</div>";
    }else{

        $receipt='';

        if(isset($_FILES['receipt']) && $_FILES['receipt']['error']==0){

            $allowed=['pdf','png','jpg','jpeg'];
            $ext=strtolower(pathinfo($_FILES['receipt']['name'],PATHINFO_EXTENSION));

            if(in_array($ext,$allowed)){

                if(!is_dir('uploads/receipts')){
                    mkdir('uploads/receipts',0777,true);
                }

                $receipt='uploads/receipts/'.time().'_'.preg_replace('/[^A-Za-z0-9._-]/','_',$_FILES['receipt']['name']);
                move_uploaded_file($_FILES['receipt']['tmp_name'],$receipt);
            }
        }

        $stmt=$conn->prepare("SELECT id,quantity FROM products WHERE product_type=? AND brand_name=? LIMIT 1");
        $stmt->bind_param("ss",$product_type,$brand_name);
        $stmt->execute();
        $result=$stmt->get_result();

        if($result->num_rows){
            $p=$result->fetch_assoc();
            $newQty=$p['quantity']+$quantity;

            $up=$conn->prepare("UPDATE products SET quantity=? WHERE id=?");
            $up->bind_param("ii",$newQty,$p['id']);
            $up->execute();

        }else{

            $ins=$conn->prepare("
            INSERT INTO products(product_name,product_type,brand_name,quantity,price)
            VALUES(?,?,?,?,0)");
            $ins->bind_param("sssi",$product_type,$product_type,$brand_name,$quantity);
            $ins->execute();
        }

        $hist=$conn->prepare("
        INSERT INTO warehouse_receiving
        (vendor_id,product_type,brand_name,quantity,receipt)
        VALUES(?,?,?,?,?)");
        $hist->bind_param("issis",$vendor_id,$product_type,$brand_name,$quantity,$receipt);
        $hist->execute();

        $message="<div class='success'>Product received successfully.</div>";
    }
}

/* ================= RECEIVING HISTORY ================= */
$sql="
SELECT wr.*,v.vendor_name
FROM warehouse_receiving wr
LEFT JOIN vendors v ON v.id=wr.vendor_id
WHERE 1=1
";

$params=[];
$types='';

if($search!=''){
    $sql.=" AND (v.vendor_name LIKE ? OR wr.product_type LIKE ? OR wr.brand_name LIKE ?)";
    $like="%$search%";
    $params[]=&$like; $params[]=&$like; $params[]=&$like;
    $types.="sss";
}

if($date_from!=''){
    $sql.=" AND DATE(wr.received_date)>=?";
    $params[]=&$date_from;
    $types.="s";
}

if($date_to!=''){
    $sql.=" AND DATE(wr.received_date)<=?";
    $params[]=&$date_to;
    $types.="s";
}

$sql.=" ORDER BY wr.received_date DESC";

$stmt=$conn->prepare($sql);

if($types!=''){
    array_unshift($params,$types);
    call_user_func_array([$stmt,'bind_param'],$params);
}

$stmt->execute();
$receivingHistory=$stmt->get_result();

/* ================= LOW STOCK ================= */
$lowStock=$conn->query("SELECT * FROM products WHERE quantity<=$low_stock_limit ORDER BY quantity ASC");

include 'includes/header.php';
include 'includes/navbar.php';
include 'includes/sidebar.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.card{background:#fff;padding:20px;margin:20px 0;border-radius:8px}
.success{background:#d4edda;padding:10px}
.error{background:#f8d7da;padding:10px}
table{width:100%;border-collapse:collapse}
th,td{border:1px solid #ddd;padding:8px}
.alert{background:#fff3cd;padding:10px;margin-bottom:15px}

.btn-edit{
    background:#007bff;
    color:#fff;
    padding:6px 10px;
    text-decoration:none;
    border-radius:4px;
    margin-right:5px;
}

.btn-delete{
    background:#dc3545;
    color:#fff;
    padding:6px 10px;
    text-decoration:none;
    border-radius:4px;
}

.btn-edit:hover,
.btn-delete:hover{
    opacity:.85;
}
</style>
</head>
<body>

<div class="main-content">

<?php echo $message; ?>

<div class="card">
<h3>Low Stock Alerts</h3>
<?php while($ls=$lowStock->fetch_assoc()){ ?>
<div class="alert">
<?php echo htmlspecialchars($ls['product_name']); ?> :
<?php echo (int)$ls['quantity']; ?> remaining
</div>
<?php } ?>
</div>

<div class="card">
<h2>Warehouse Receiving</h2>

<form method="post" enctype="multipart/form-data">

<select name="product_type" id="productTypeSelect" required>
<option value="">Select Product Type</option>
<?php while($t=$productTypes->fetch_assoc()){ ?>
<option value="<?php echo htmlspecialchars($t['product_type']); ?>">
<?php echo htmlspecialchars($t['product_type']); ?>
</option>
<?php } ?>
</select>

<select name="brand_name" id="brandSelect" required></select>
<select name="vendor_id" id="vendorSelect" required></select>

<input type="text" id="phone" readonly placeholder="Vendor Phone">
<input type="text" id="email" readonly placeholder="Vendor Email">
<textarea id="address" readonly placeholder="Vendor Address"></textarea>

<label for="quantity">Quantity (Number of Items)</label>
<input type="number" id="quantity" name="quantity" min="1" required>
<input type="file" name="receipt" accept=".pdf,.png,.jpg,.jpeg">

<button type="submit" name="receive">Receive Product</button>
</form>
</div>

<div class="card">
<h2>Receiving History</h2>

<form method="get">
<label for="quantity">Enter Search Information</label>
<input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>">
<input type="date" name="date_from" value="<?php echo htmlspecialchars($date_from); ?>">
<input type="date" name="date_to" value="<?php echo htmlspecialchars($date_to); ?>">
<button type="submit">Search</button>
</form>

<table>
<tr>
<th>Date</th>
<th>Vendor</th>
<th>Type</th>
<th>Brand</th>
<th>Qty</th>
<th>Receipt</th>
<th>Actions</th>
</tr>

<?php while($row=$receivingHistory->fetch_assoc()){ ?>
<tr>
    <td><?php echo $row['received_date']; ?></td>
    <td><?php echo htmlspecialchars($row['vendor_name']); ?></td>
    <td><?php echo htmlspecialchars($row['product_type']); ?></td>
    <td><?php echo htmlspecialchars($row['brand_name']); ?></td>
    <td><?php echo number_format($row['quantity']); ?></td>

    <td>
        <?php if($row['receipt']){ ?>
            <a href="<?php echo $row['receipt']; ?>" target="_blank">View</a>
        <?php }else{ ?>
            No Receipt
        <?php } ?>
    </td>

    <td>
        <a href="edit_receiving.php?id=<?php echo $row['id']; ?>" class="btn-edit">
            Edit
        </a>

        <a href="delete_receiving.php?id=<?php echo $row['id']; ?>"
           class="btn-delete"
           onclick="return confirm('Are you sure you want to delete this record?');">
            Delete
        </a>
    </td>
</tr>
<?php } ?>
</table>
</div>

</div>

<script>
let allProducts = <?php echo json_encode($allProducts); ?>;

function loadBrands(){
let type=document.getElementById('productTypeSelect').value;
let brand=document.getElementById('brandSelect');
brand.innerHTML='<option value="">Select Brand</option>';

let brands=[];

allProducts.forEach(p=>{
if(p.product_type===type && !brands.includes(p.brand_name)){
brands.push(p.brand_name);
}
});

brands.forEach(b=>{
let o=document.createElement('option');
o.value=b;
o.textContent=b;
brand.appendChild(o);
});

loadVendors();
}

function loadVendors(){
let type=document.getElementById('productTypeSelect').value;
let brand=document.getElementById('brandSelect').value;

let vendor=document.getElementById('vendorSelect');
vendor.innerHTML='<option value="">Select Vendor</option>';

let used=[];

allProducts.forEach(p=>{

if(p.product_type===type && p.brand_name===brand){

if(!used.includes(p.vendor_id)){
used.push(p.vendor_id);

let o=document.createElement('option');
o.value=p.vendor_id;
o.textContent=p.vendor_name;
o.dataset.phone=p.vendor_phone;
o.dataset.email=p.vendor_email;
o.dataset.address=p.vendor_address;
vendor.appendChild(o);
}
}
});
}

document.getElementById('productTypeSelect').addEventListener('change',loadBrands);
document.getElementById('brandSelect').addEventListener('change',loadVendors);

document.getElementById('vendorSelect').addEventListener('change',function(){
let s=this.options[this.selectedIndex];
document.getElementById('phone').value=s.dataset.phone||'';
document.getElementById('email').value=s.dataset.email||'';
document.getElementById('address').value=s.dataset.address||'';
});
</script>

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