<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$username = $_SESSION['username'] ?? 'Guest';
$allowed_roles = ['admin','stores','finance'];
$user_role = $_SESSION['role'] ?? 'guest';

function canManageMenu(){
    global $user_role, $allowed_roles;
    return in_array($user_role, $allowed_roles);
}

// ================= HANDLE FORM SUBMISSION =================
if(isset($_POST['report_damage'])){
    $product_id    = intval($_POST['product_id']);
    $department_id = intval($_POST['department_id']);
    $qty           = intval($_POST['quantity']);
    $reason        = $conn->real_escape_string($_POST['reason']);
    $reported_by   = $username;
    $reported_at   = date('Y-m-d H:i:s');

    // Check current stock
   $stock_check = $conn->prepare("
   SELECT COALESCE(SUM(quantity),0) AS total_qty
    FROM product_stock 
    WHERE product_id=? AND department_id=5
");
    $stock_check->bind_param("i", $product_id);
    $stock_check->execute();
    $available_qty = $stock_check->get_result()->fetch_assoc()['total_qty'];

    if($qty <= 0){
        $error = "Quantity must be greater than 0.";
    } elseif($qty > $available_qty){
        $error = "Cannot report more than available stock ($available_qty).";
    } else {
        // Insert damaged goods
        $stmt = $conn->prepare("
            INSERT INTO damaged_goods
            (product_id, department_id, quantity, reason, reported_by, reported_at)
            VALUES (?,?,?,?,?,?)
        ");
        $stmt->bind_param("iiisss", $product_id, $department_id, $qty, $reason, $reported_by, $reported_at);
        if($stmt->execute()){
            // Deduct from stock
            $remaining = $qty;
            while($remaining > 0){
                $stock_row = $conn->query("
                    SELECT id, quantity FROM product_stock
                    WHERE product_id=$product_id AND department_id=$department_id AND quantity>0
                    ORDER BY id ASC LIMIT 1
                ")->fetch_assoc();
                if(!$stock_row) break;
                $deduct = min($remaining, $stock_row['quantity']);
                $upd = $conn->prepare("UPDATE product_stock SET quantity = quantity - ? WHERE id=?");
                $upd->bind_param("ii", $deduct, $stock_row['id']);
                $upd->execute();
                $remaining -= $deduct;
            }

            $success = "Damaged goods recorded successfully.";

            // Optional: Send email
            $prod_info = $conn->query("SELECT name, sku FROM products WHERE id=$product_id")->fetch_assoc();
            $dept_info = $conn->query("SELECT name FROM departments WHERE id=$department_id")->fetch_assoc();
            $to = "giantplusmw@gmail.com,rams.investments@gmail.com";
            $subject = "Damaged Goods Alert: {$prod_info['name']} ({$prod_info['sku']})";
            $message = "
                <h3>Damaged Goods Reported</h3>
                <p><strong>Product:</strong> {$prod_info['name']} ({$prod_info['sku']})</p>
                <p><strong>Quantity:</strong> $qty</p>
                <p><strong>Department:</strong> {$dept_info['name']}</p>
                <p><strong>Reason:</strong> $reason</p>
                <p><strong>Reported By:</strong> $username</p>
                <p><strong>Time:</strong> $reported_at</p>
            ";
            $headers  = "MIME-Version: 1.0\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8\r\n";
            $headers .= "From: cloud@gianterp.space\r\n";
            mail($to, $subject, $message, $headers);
        } else {
            $error = "Failed to record damaged goods.";
        }
    }
}

// ================= FETCH PRODUCTS & DEPARTMENTS =================
$products = $conn->query("SELECT id, name, sku FROM products ORDER BY name");
$departments = $conn->query("SELECT id, name FROM departments ORDER BY name");

// ================= FETCH RECENT DAMAGED GOODS =================
$recent_damages = $conn->query("
    SELECT dg.*, p.name AS product_name, p.sku, d.name AS dept_name 
    FROM damaged_goods dg
    JOIN products p ON dg.product_id = p.id
    JOIN departments d ON dg.department_id = d.id
    ORDER BY dg.reported_at DESC
    LIMIT 20
");
?>

<div class="container mt-4">
    <h3 class="text-center">🛑 Record Damaged Goods</h3>
    <hr>

    <?php if(isset($error)): ?>
        <div class="alert alert-danger"><?= $error ?></div>
    <?php endif; ?>
    <?php if(isset($success)): ?>
        <div class="alert alert-success"><?= $success ?></div>
    <?php endif; ?>

    <form method="POST" class="row g-3 mb-4">
        <div class="col-md-4">
            <label for="product_id" class="form-label">Product</label>
            <select name="product_id" id="product_id" class="form-control" required>
                <option value="">-- Select Product --</option>
                <?php
                $products->data_seek(0);
                while($p = $products->fetch_assoc()):
                    // Get total quantity per product
                    $qty_res = $conn->query("
                        SELECT COALESCE(SUM(quantity),0) AS total_qty 
                        FROM product_stock 
                        WHERE product_id={$p['id']}
                    ")->fetch_assoc();
                    $total_qty = intval($qty_res['total_qty']);
                ?>
                <option value="<?= $p['id'] ?>">
                    <?= htmlspecialchars($p['name']) ?> (<?= $p['sku'] ?>) - Stock: <?= $total_qty ?>
                </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div class="col-md-4">
            <label for="department_id" class="form-label">Department</label>
           <!-- MAIN STORE DEFAULT -->
<input type="hidden" name="department_id" value="5">

<div class="form-control bg-light">
    Main Store
</div>
        </div>

        <div class="col-md-2">
            <label for="quantity" class="form-label">Quantity</label>
            <input type="number" name="quantity" id="quantity" class="form-control" min="1" required>
        </div>

        <div class="col-md-2">
            <label for="reason" class="form-label">Damage Type</label>
            <select name="reason" id="reason" class="form-control" required>
                <option value="">-- Select Reason --</option>
                <option value="Broken">Broken</option>
                <option value="Expired">Expired</option>
                <option value="Spoiled">Spoiled</option>
                <option value="Lost">Lost</option>
                <option value="Other">Other</option>
            </select>
        </div>

        <div class="col-md-12">
            <button type="submit" name="report_damage" class="btn btn-danger">
                <i class="fa fa-exclamation-triangle"></i> Record Damaged
            </button>
            <a href="inventory_data.php" class="btn btn-secondary">Back to Inventory</a>
        </div>
    </form>

    <!-- ================= RECENT DAMAGED GOODS ================= -->
    <h4>Recent Damaged Goods</h4>
    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white">
            <tr>
                <th>Product</th>
                <th>SKU</th>
                <th>Department</th>
                <th>Quantity</th>
                <th>Reason</th>
                <th>Reported By</th>
                <th>Reported At</th>
            </tr>
        </thead>
        <tbody>
            <?php while($d = $recent_damages->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($d['product_name']) ?></td>
                <td><?= $d['sku'] ?></td>
                <td><?= htmlspecialchars($d['dept_name']) ?></td>
                <td><?= intval($d['quantity']) ?></td>
                <td><?= htmlspecialchars($d['reason']) ?></td>
                <td><?= htmlspecialchars($d['reported_by']) ?></td>
                <td><?= date('Y-m-d H:i', strtotime($d['reported_at'])) ?></td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

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