<?php
session_start();
require_once '../../config/db_connect.php';

// Redirect if not logged in
if (!isset($_SESSION['user'])) {
    header('Location: ../../index.php');
    exit;
}

$message = '';

// Check if batch ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    die('Batch ID is missing.');
}
$batch_id = intval($_GET['id']);

// Fetch batch details
try {
    $stmt = $pdo->prepare("
        SELECT pb.*, p.name AS product_name
        FROM product_batches pb
        JOIN products p ON pb.product_id = p.id
        WHERE pb.id = ?
    ");
    $stmt->execute([$batch_id]);
    $batch = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$batch) {
        die('Batch not found.');
    }
} catch (PDOException $e) {
    die("Error loading batch: " . htmlspecialchars($e->getMessage()));
}

// Fetch products for dropdown
$products = $pdo->query("SELECT id, name FROM products ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

// Handle form update
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id   = $_POST['product_id'];
    $batch_no     = $_POST['batch_no'];
    $expiry_date  = $_POST['expiry_date'];
    $quantity     = $_POST['quantity'];
    $buying_price = $_POST['buying_price'];
    $selling_price= $_POST['selling_price'];
    $supplier_id  = $_POST['supplier_id'] ?? null; // if you have supplier field
    $updated_by   = $_SESSION['user']['id'];

    try {
        $update = $pdo->prepare("
            UPDATE product_batches 
            SET product_id = :product_id,
                batch_no = :batch_no,
                qty = :qty,
                cost_price = :cost_price,
                sell_price = :sell_price,
                expiry_date = :expiry_date,
                supplier_id = :supplier_id,
                updated_by = :updated_by,
                updated_at = NOW()
            WHERE id = :id
        ");

        $update->execute([
            ':product_id'  => $product_id,
            ':batch_no'    => $batch_no,
            ':qty'         => $quantity,
            ':cost_price'  => $buying_price,
            ':sell_price'  => $selling_price,
            ':expiry_date' => $expiry_date,
            ':supplier_id' => $supplier_id,
            ':updated_by'  => $updated_by,
            ':id'          => $batch_id
        ]);

        $message = '<div class="alert alert-success">✅ Batch updated successfully!</div>';

        // Refresh batch data
        $stmt = $pdo->prepare("
            SELECT pb.*, p.name AS product_name
            FROM product_batches pb
            JOIN products p ON pb.product_id = p.id
            WHERE pb.id = ?
        ");
        $stmt->execute([$batch_id]);
        $batch = $stmt->fetch(PDO::FETCH_ASSOC);

    } catch (PDOException $e) {
        $message = '<div class="alert alert-danger">❌ Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Batch | Pharmacy</title>
    <link rel="stylesheet" href="../../libraries/bootstrap.css">
</head>
<body class="bg-light p-4">

<div class="container mt-4">
    <div class="card shadow-sm">
        <div class="card-header bg-success text-white d-flex justify-content-between align-items-center">
            <h4 class="mb-0"><i class="fas fa-boxes"></i> Edit Product Batch</h4>
            <a href="view_batches.php" class="btn btn-light btn-sm">← Back to Batches</a>
        </div>
        <div class="card-body">
            <?= $message ?>
            <form method="POST" autocomplete="off">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label>Product</label>
                        <select name="product_id" class="form-control" required>
                            <option value="">-- Select Product --</option>
                            <?php foreach ($products as $p): ?>
                                <option value="<?= $p['id'] ?>" <?= ($p['id'] == $batch['product_id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($p['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="col-md-6 mb-3">
                        <label>Batch No</label>
                        <input type="text" name="batch_no" value="<?= htmlspecialchars($batch['batch_no']) ?>" class="form-control" required>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Expiry Date</label>
                        <input type="date" name="expiry_date" value="<?= htmlspecialchars($batch['expiry_date']) ?>" class="form-control" required>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Quantity</label>
                        <input type="number" name="quantity" value="<?= htmlspecialchars($batch['qty']) ?>" class="form-control" required>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Buying Price</label>
                        <input type="number" step="0.01" name="buying_price" value="<?= htmlspecialchars($batch['cost_price']) ?>" class="form-control" required>
                    </div>

                    <div class="col-md-4 mb-3">
                        <label>Selling Price</label>
                        <input type="number" step="0.01" name="selling_price" value="<?= htmlspecialchars($batch['sell_price']) ?>" class="form-control" required>
                    </div>

                    <?php if (isset($batch['supplier_id'])): ?>
                    <div class="col-md-6 mb-3">
                        <label>Supplier</label>
                        <input type="number" name="supplier_id" value="<?= htmlspecialchars($batch['supplier_id']) ?>" class="form-control">
                    </div>
                    <?php endif; ?>
                </div>

                <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> Save Changes</button>
            </form>
        </div>
    </div>
</div>

<!-- FontAwesome for icons -->
<script src="../../libraries/fontawesome-free-6.0.0-beta2-web/js/all.min.js"></script>
</body>
</html>
