<?php

ini_set('display_errors',1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../includes/auth.php';
requireLogin();
requirePermission('inventory_returns_view');

require_once __DIR__ . '/../../config/database.php';

require_once __DIR__ . '/../../includes/header.php';
require_once __DIR__ . '/../../includes/sidebar.php';

/* -------------------------------
SESSION TENANT
--------------------------------*/

$company_id = $_SESSION['company_id'] ?? 0;

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

/* -------------------------------
LOAD RETURN HEADER
TENANT SAFE
--------------------------------*/

$stmt = $pdo->prepare("
SELECT *
FROM inventory_returns
WHERE id = ?
AND company_id = ?
");

$stmt->execute([$id,$company_id]);

$return = $stmt->fetch();

if(!$return){
echo "<div class='main-content'>";
echo "<div class='stat-card'>";
echo "<h3>Return not found.</h3>";
echo "<a href='index.php'><button>Back</button></a>";
echo "</div>";
echo "</div>";
require_once __DIR__ . '/../../includes/footer.php';
exit;
}

/* -------------------------------
STATUS COLOR (InfraCore UI)
--------------------------------*/

$statusColor = "#999";

if($return['status']=="Pending"){
$statusColor = "#f2531e"; // EDM Orange
}

if($return['status']=="Approved"){
$statusColor = "#007bff"; // Blue
}

if($return['status']=="Closed"){
$statusColor = "#28a745"; // Green
}

/* -------------------------------
UPDATE STATUS
--------------------------------*/

if(isset($_POST['update_status'])){

$newStatus = $_POST['status'];

$pdo->beginTransaction();

try{

/* update status */

$stmt = $pdo->prepare("
UPDATE inventory_returns
SET status = ?
WHERE id = ?
AND company_id = ?
");

$stmt->execute([$newStatus,$id,$company_id]);

/* -------------------------------
IF APPROVED → ADD STOCK
--------------------------------*/

if($return['status'] != "Approved" && $newStatus == "Approved"){

$stmt = $pdo->prepare("
SELECT product_id, quantity
FROM inventory_return_items
WHERE return_id = ?
");

$stmt->execute([$id]);
$returnItems = $stmt->fetchAll();

foreach($returnItems as $item){

$updateStock = $pdo->prepare("
UPDATE inventory_products
SET stock_qty = stock_qty + ?
WHERE id = ?
");

$updateStock->execute([
$item['quantity'],
$item['product_id']
]);

}

}

$pdo->commit();

header("Location: view.php?id=".$id);
exit;

}catch(Exception $e){

$pdo->rollBack();
echo "Error updating status.";

}

}

/* -------------------------------
LOAD RETURN ITEMS
--------------------------------*/

$stmt = $pdo->prepare("
SELECT 
inventory_return_items.*,
inventory_products.product_name
FROM inventory_return_items
LEFT JOIN inventory_products
ON inventory_return_items.product_id = inventory_products.id
WHERE return_id = ?
");

$stmt->execute([$id]);
$items = $stmt->fetchAll();

?>

<div class="main-content">

<div class="page-header">
<h2>Return Details</h2>
</div>

<div class="stat-card">

<h3>Return Information</h3>

<table class="table">

<tr>
<td><strong>Return Number</strong></td>
<td><?php echo $return['return_number']; ?></td>
</tr>

<tr>
<td><strong>Return Type</strong></td>
<td><?php echo $return['return_type']; ?></td>
</tr>

<tr>
<td><strong>Status</strong></td>

<td>

<div style="
display:inline-block;
padding:6px 14px;
border-radius:20px;
background:<?php echo $statusColor; ?>;
color:#fff;
font-weight:600;
margin-bottom:8px;
">
<?php echo $return['status']; ?>
</div>

<br>

<form method="POST" style="display:flex; gap:10px; align-items:center;">

<select name="status">

<option value="Pending" <?php if($return['status']=="Pending") echo "selected"; ?>>Pending</option>

<option value="Approved" <?php if($return['status']=="Approved") echo "selected"; ?>>Approved</option>

<option value="Closed" <?php if($return['status']=="Closed") echo "selected"; ?>>Closed</option>

</select>

<button type="submit" name="update_status">Update</button>

</form>

</td>
</tr>

<tr>
<td><strong>Reason</strong></td>
<td><?php echo $return['reason']; ?></td>
</tr>

<tr>
<td><strong>Date Created</strong></td>
<td><?php echo $return['created_at']; ?></td>
</tr>

</table>

<br>

<h3>Returned Products</h3>

<table class="table">

<thead>

<tr>
<th>Product</th>
<th>Quantity</th>
<th>Condition</th>
<th>Notes</th>
</tr>

</thead>

<tbody>

<?php if(empty($items)): ?>

<tr>
<td colspan="4">No items found.</td>
</tr>

<?php else: ?>

<?php foreach($items as $item): ?>

<tr>

<td><?php echo $item['product_name']; ?></td>

<td><?php echo $item['quantity']; ?></td>

<td><?php echo $item['condition']; ?></td>

<td><?php echo $item['notes']; ?></td>

</tr>

<?php endforeach; ?>

<?php endif; ?>

</tbody>

</table>

<br>

<a href="edit.php?id=<?php echo $return['id']; ?>">
<button class="btn-primary">Edit Return</button>
</a>

<br><br>

<a href="index.php">
<button class="btn-small">Back to Returns</button>
</a>

</div>

</div>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>