<?php

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

require_once __DIR__ . '/../../includes/auth.php';
requireLogin();
requirePermission('inventory_returns_create');
require_once __DIR__ . '/../../config/database.php';

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

$message = "";

/* -------------------------------
GET SESSION DATA
--------------------------------*/

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

/* -------------------------------
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();

/* -------------------------------
GENERATE RETURN NUMBER
(Tenant Safe)
--------------------------------*/

$stmt = $pdo->prepare("
SELECT id
FROM inventory_returns
WHERE company_id = ?
ORDER BY id DESC
LIMIT 1
");

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

$last = $stmt->fetch();

$next_id = $last ? $last['id'] + 1 : 1;

$return_number = 'RET-' . str_pad($next_id,5,'0',STR_PAD_LEFT);

/* -------------------------------
SAVE RETURN
--------------------------------*/

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

$pdo->beginTransaction();

try{

$stmt = $pdo->prepare("
INSERT INTO inventory_returns
(company_id, return_number, return_type, notes, status, created_by, created_at)
VALUES (?,?,?,?,?,?,NOW())
");

$stmt->execute([
$company_id,
$_POST['return_number'],
$_POST['return_type'],
$_POST['reason'],
'Pending',
$user_id
]);

$return_id = $pdo->lastInsertId();

/* -------------------------------
SAVE RETURN ITEMS
--------------------------------*/

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([
$return_id,
$product_id,
$_POST['quantity'][$index],
$_POST['condition'][$index],
'Pending',
$_POST['notes'][$index]
]);

}

$pdo->commit();

$message = "Return created successfully.";

}catch(Exception $e){

$pdo->rollBack();
$message = "Error creating return.";

}

}

?>

<div class="main-content">

<h2>Create Sales Inventory Return</h2>

<?php if($message): ?>
<div class="alert">
<?php echo $message; ?>
</div>
<?php endif; ?>

<div class="card">

<form method="POST">

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

<div class="form-group">
<label>Return Type</label>
<select name="return_type">
<option value="Sales Inventory Return">Sales Inventory Return</option>
</select>
</div>

<div class="form-group">
<label>Reason for Return</label>
<textarea name="reason" required></textarea>
</div>

<hr>

<h3>Return Items</h3>

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

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

<tr>

<td>
<select name="product_id[]">
<option value="">Select Product</option>
<?php foreach($products as $product): ?>
<option value="<?php echo $product['id']; ?>">
<?php echo $product['product_name']; ?>
</option>
<?php endforeach; ?>
</select>
</td>

<td>
<input type="number" name="quantity[]" min="1">
</td>

<td>
<select name="condition[]">
<option value="GOOD">GOOD</option>
<option value="FAULTY">FAULTY</option>
<option value="DAMAGED">DAMAGED</option>
</select>
</td>

<td>
<input type="text" name="notes[]">
</td>

<td>
<button type="button" onclick="removeRow(this)">Remove</button>
</td>

</tr>

</table>

<br>

<button type="button" onclick="addRow()">Add Product</button>

<br><br>

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

</form>

</div>

</div>

<script>

function addRow(){

var table = document.getElementById("items_table");

var row = table.insertRow();

row.innerHTML = `
<td>
<select name="product_id[]">
<option value="">Select Product</option>
<?php foreach($products as $product): ?>
<option value="<?php echo $product['id']; ?>">
<?php echo $product['product_name']; ?>
</option>
<?php endforeach; ?>
</select>
</td>

<td>
<input type="number" name="quantity[]" min="1">
</td>

<td>
<select name="condition[]">
<option value="GOOD">GOOD</option>
<option value="FAULTY">FAULTY</option>
<option value="DAMAGED">DAMAGED</option>
</select>
</td>

<td>
<input type="text" name="notes[]">
</td>

<td>
<button type="button" onclick="removeRow(this)">Remove</button>
</td>
`;

}

function removeRow(button){

var row = button.parentNode.parentNode;

row.parentNode.removeChild(row);

}

</script>

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