<?php

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

require_once __DIR__ . '/../../includes/auth.php';
requireLogin();
requirePermission('inventory_returns_edit');
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 (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'><div class='stat-card'>Return not found.</div></div>";
require_once __DIR__ . '/../../includes/footer.php';
exit;
}

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

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

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

$items = $stmt->fetchAll();

/* -------------------------------
LOAD PRODUCTS (TENANT SAFE)
--------------------------------*/

$product_stmt = $pdo->prepare("
SELECT id, product_name
FROM inventory_products
WHERE status = 'active'
AND company_id = ?
ORDER BY product_name ASC
");

$product_stmt->execute([$company_id]);

$products = $product_stmt->fetchAll();

/* -------------------------------
SAVE UPDATE
--------------------------------*/

if($_SERVER['REQUEST_METHOD'] === 'POST'){

$pdo->beginTransaction();

try{

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

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

$pdo->prepare("DELETE FROM inventory_return_items WHERE return_id=?")->execute([$id]);

foreach($_POST['product_id'] as $index=>$product_id){

if(empty($product_id)) continue;

$stmt = $pdo->prepare("
INSERT INTO inventory_return_items
(return_id,product_id,quantity,`condition`,status,notes)
VALUES (?,?,?,?,?,?)
");

$stmt->execute([
$id,
$product_id,
$_POST['quantity'][$index],
$_POST['condition'][$index],
'Pending',
$_POST['notes'][$index]
]);

}

$pdo->commit();

echo "<script>window.location='view.php?id=".$id."';</script>";

}catch(Exception $e){

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

}

}

?>

<div class="main-content">

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

<div class="stat-card">

<form method="POST">

<div class="form-group">
<label>Return Number</label>
<input type="text" value="<?php echo $return['return_number']; ?>" readonly>
</div>

<div class="form-group">
<label>Reason</label>
<textarea name="reason"><?php echo $return['reason']; ?></textarea>
</div>

<hr>

<h3>Return Items</h3>

<table width="100%" border="1" cellpadding="5">

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

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

<tr>

<td>

<select name="product_id[]">

<?php foreach($products as $product): ?>

<option value="<?php echo $product['id']; ?>"
<?php if($product['id']==$item['product_id']) echo "selected"; ?>>
<?php echo $product['product_name']; ?>
</option>

<?php endforeach; ?>

</select>

</td>

<td>
<input type="number" name="quantity[]" value="<?php echo $item['quantity']; ?>">
</td>

<td>
<select name="condition[]">
<option <?php if($item['condition']=="GOOD") echo "selected"; ?>>GOOD</option>
<option <?php if($item['condition']=="FAULTY") echo "selected"; ?>>FAULTY</option>
<option <?php if($item['condition']=="DAMAGED") echo "selected"; ?>>DAMAGED</option>
</select>
</td>

<td>
<input type="text" name="notes[]" value="<?php echo $item['notes']; ?>">
</td>

</tr>

<?php endforeach; ?>

</table>

<br>

<button type="submit">Update Return</button>

</form>

</div>

</div>

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