<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'php_errors.log');

session_start();
require_once("../config/config.php");

if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'store manager'])) {
    header("Location: ../login.php");
    exit();
}

$inventory_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$confirmed = isset($_GET['confirm']) && $_GET['confirm'] === 'yes';

$error = "";
$success = "";

// Fetch Material Details for Confirmation
$stmt = $conn->prepare("
    SELECT im.sku, im.name, im.current_stock, 
           w.warehouse_name 
    FROM inventory_master im
    LEFT JOIN warehouse_master w ON im.warehouse_id = w.id
    WHERE im.id = ?
");
$stmt->bind_param("i", $inventory_id);
$stmt->execute();
$material = $stmt->get_result()->fetch_assoc();

if (!$material) {
    $error = "Material not found or already deleted.";
}

// ====================== DELETE LOGIC ======================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $inventory_id > 0) {
    if (isset($_POST['confirm_delete']) && $_POST['confirm_delete'] === 'yes') {
        try {
            $conn->begin_transaction();

            // Delete serial numbers first (foreign key)
            $conn->query("DELETE FROM inventory_serials WHERE inventory_id = $inventory_id");

            // Delete main inventory record
            $stmt = $conn->prepare("DELETE FROM inventory_master WHERE id = ?");
            $stmt->bind_param("i", $inventory_id);
            $stmt->execute();

            $conn->commit();

            $success = "Material '{$material['name']}' (SKU: {$material['sku']}) has been successfully deleted.";

            // Optional: Redirect after 3 seconds
            header("Refresh: 1; url=inventory_list.php");
            
        } catch (Exception $e) {
            $conn->rollback();
            if (strpos($e->getMessage(), 'foreign key constraint') !== false) {
                $error = "Cannot delete this material because it is linked with existing records (like delivery challans). Please deactivate it instead.";
            } else {
                $error = "Something went wrong while deleting. Please try again.";
            }

            error_log("Delete Error: " . $e->getMessage());
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Delete Material</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root {
            --primary: #a855f7;
            --accent: #c084fc;
            --glass: rgba(255,255,255,0.10);
            --glass-border: rgba(255,255,255,0.20);
            --danger: #ef4444;
        }
        * { margin:0; padding:0; box-sizing:border-box; }
        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: linear-gradient(135deg, rgba(0,0,0,0.78), rgba(0,0,0,0.92)), url('../background.jpeg') center/cover fixed;
            color: #f1f5f9;
            padding: 20px 15px;
            min-height: 100vh;
        }
        .container { max-width: 700px; margin: auto; }

        .glass-container {
            background: var(--glass);
            backdrop-filter: blur(24px);
            border-radius: 32px;
            border: 1px solid var(--glass-border);
            box-shadow: 0 25px 80px rgba(0,0,0,0.65);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(90deg, rgba(239,68,68,0.35), rgba(185,28,28,0.25));
            padding: 50px 40px;
            text-align: center;
            position: relative;
        }
        .header h1 { 
            font-size: clamp(28px, 5vw, 40px); 
            font-weight: 700; 
            color: #fecaca;
        }

        .form-area { padding: 50px 40px; text-align: center; }

        .warning-card {
            background: rgba(239,68,68,0.15);
            border: 2px solid rgba(239,68,68,0.6);
            border-radius: 20px;
            padding: 35px;
            margin-bottom: 30px;
        }

        .material-info {
            background: rgba(255,255,255,0.08);
            border-radius: 16px;
            padding: 25px;
            margin: 25px 0;
            text-align: left;
        }

        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 12px 0;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        .info-row:last-child { border-bottom: none; }

        .label { color: #c4b5fd; font-weight: 500; }
        .value { font-weight: 600; color: #f1f5f9; }

        .btn {
            padding: 16px 32px;
            border-radius: 16px;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            margin: 10px;
            transition: all 0.3s;
        }

        .btn-cancel {
            background: rgba(255,255,255,0.15);
            color: white;
            border: 1px solid rgba(255,255,255,0.4);
        }

        .btn-delete {
            background: linear-gradient(135deg, var(--danger), #b91c1c);
            color: white;
            border: none;
        }

        .btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        }

        .message {
            padding: 18px 24px;
            border-radius: 16px;
            margin-bottom: 25px;
            font-weight: 600;
        }
        .success { background: rgba(34,197,94,0.25); border:1px solid #4ade80; color:#86efac; }
        .error   { background: rgba(239,68,68,0.25); border:1px solid #f87171; color:#fca5a5; }

        @media (max-width: 768px) {
            .form-area { padding: 30px 20px; }
        }
    </style>
</head>
<body>

<?php include '../config/header.php'; ?>

<div class="container">
    <div class="glass-container">
        <div class="header">
            <a href="inventory_list.php" style="color:#fed7aa; text-decoration:none; position:absolute; left:40px; top:40px;">
                ← Back to Inventory
            </a>
            <h1><i class="fas fa-trash-alt"></i> Delete Material</h1>
        </div>

        <div class="form-area">
            <?php if ($success): ?>
                <div class="message success">
                    <?= htmlspecialchars($success) ?><br><br>
                    <small>Redirecting to inventory list in 3 seconds...</small>
                </div>
            <?php elseif ($error): ?>
                <div class="message error"><?= htmlspecialchars($error) ?></div>
            <?php else: ?>

            <div class="warning-card">
                <i class="fas fa-exclamation-triangle" style="font-size:3rem; color:#f87171; margin-bottom:15px;"></i>
                <h2 style="color:#fecaca; margin-bottom:10px;">Warning: This action cannot be undone!</h2>
                <p style="color:#fda4af; max-width:500px; margin:auto;">
                    You are about to permanently delete this material and all its associated serial numbers.
                </p>
            </div>

            <div class="material-info">
                <div class="info-row">
                    <span class="label">SKU</span>
                    <span class="value"><?= htmlspecialchars($material['sku'] ?? 'N/A') ?></span>
                </div>
                <div class="info-row">
                    <span class="label">Material Name</span>
                    <span class="value"><?= htmlspecialchars($material['name'] ?? 'N/A') ?></span>
                </div>
                <div class="info-row">
                    <span class="label">Warehouse</span>
                    <span class="value"><?= htmlspecialchars($material['warehouse_name'] ?? 'N/A') ?></span>
                </div>
                <div class="info-row">
                    <span class="label">Current Stock</span>
                    <span class="value" style="color:#4ade80;">
                        <?= number_format($material['current_stock'] ?? 0, 2) ?>
                    </span>
                </div>
            </div>

            <p style="color:#f87171; font-weight:600; margin:25px 0;">
                Are you sure you want to delete this material?
            </p>

            <form method="POST">
                <input type="hidden" name="confirm_delete" value="yes">
                
                <div>
                    <button type="button" onclick="window.location.href='inventory-management.php'" class="btn btn-cancel">
                        <i class="fas fa-times"></i> Cancel
                    </button>
                    
                    <button type="submit" class="btn btn-delete" onclick="return confirm('FINAL WARNING: Delete this material permanently?')">
                        <i class="fas fa-trash-alt"></i> Yes, Delete Material
                    </button>
                </div>
            </form>

            <?php endif; ?>
        </div>
    </div>
</div>

</body>
</html>

<?php $conn->close(); ?>