<?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");

$success = "";
$error = "";
$material_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Fetch material details
$material = null;
if ($material_id > 0) {
    try {
        $query = "SELECT * FROM material_master WHERE id = ?";
        $stmt = $pdo->prepare($query);
        $stmt->execute([$material_id]);
        $material = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$material) {
            $error = "Material not found.";
        }
    } catch (PDOException $e) {
        $error = "Database error: " . $e->getMessage();
    }
} else {
    $error = "Invalid material ID.";
    header("Location: material-management.php");
    exit();
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && $material) {
    $sku = trim($_POST["sku"]);
    $name = trim($_POST["name"]);
    $category = trim($_POST["category"]);
    $unit = trim($_POST["unit"]);
    $stock = trim($_POST["stock"]) !== '' ? (float)$_POST["stock"] : 0;
    $reorder_level = trim($_POST["reorder_level"]) !== '' ? (float)$_POST["reorder_level"] : 0;
    $last_cost = trim($_POST["last_cost"]) !== '' ? (float)$_POST["last_cost"] : 0;

    if (empty($sku)) {
        $error = "SKU is required.";
    } elseif (empty($name)) {
        $error = "Material name is required.";
    } else {
        try {
            $query = "UPDATE material_master 
                      SET sku = ?, name = ?, category = ?, unit = ?, stock = ?, reorder_level = ?, last_cost = ?, updated_at = NOW()
                      WHERE id = ?";
            $stmt = $pdo->prepare($query);
            if ($stmt->execute([$sku, $name, $category, $unit, $stock, $reorder_level, $last_cost, $material_id])) {
                $success = "Material updated successfully.";
                // Refresh data
                $material['sku'] = $sku;
                $material['name'] = $name;
                $material['category'] = $category;
                $material['unit'] = $unit;
                $material['stock'] = $stock;
                $material['reorder_level'] = $reorder_level;
                $material['last_cost'] = $last_cost;
            } else {
                $error = "Failed to update material.";
            }
        } catch (PDOException $e) {
            if ($e->getCode() == 23000) {
                $error = "SKU already exists. Please use a unique SKU.";
            } else {
                $error = "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>Edit Material</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            background: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.6)),
                        url('../background.jpeg') center/cover no-repeat fixed;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        /* Glassmorphism Container */
        .glass-container {
            width: 100%;
            max-width: 650px;
            background: rgba(255, 255, 255, 0.12);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            border-radius: 24px;
            border: 1px solid rgba(255, 255, 255, 0.25);
            box-shadow: 0 25px 50px rgba(0, 0, 0, 0.4);
            overflow: hidden;
        }

        .header {
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            padding: 40px 30px;
            text-align: center;
            color: white;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .header h1 {
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 8px;
            text-shadow: 0 2px 10px rgba(0,0,0,0.3);
        }

        .header p {
            font-size: 16px;
            opacity: 0.9;
        }

        .form-area {
            padding: 45px 40px;
            color: white;
        }

        .message {
            padding: 16px 20px;
            border-radius: 14px;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            font-weight: 600;
            backdrop-filter: blur(8px);
        }

        .success {
            background: rgba(34, 197, 94, 0.25);
            border: 1px solid rgba(74, 222, 128, 0.4);
        }

        .error {
            background: rgba(239, 68, 68, 0.25);
            border: 1px solid rgba(252, 165, 165, 0.4);
        }

        .message i {
            margin-right: 14px;
            font-size: 22px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 28px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        label {
            margin-bottom: 10px;
            font-weight: 600;
            font-size: 15px;
        }

        .required {
            color: #fca5a5;
        }

        input[type="text"],
        input[type="number"] {
            padding: 16px 18px;
            background: rgba(255, 255, 255, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 14px;
            color: white;
            font-size: 16px;
            backdrop-filter: blur(8px);
            transition: all 0.3s ease;
        }

        input::placeholder {
            color: rgba(255, 255, 255, 0.6);
        }

        input:focus {
            outline: none;
            border-color: #a78bfa;
            background: rgba(255, 255, 255, 0.25);
            box-shadow: 0 0 0 4px rgba(167, 139, 250, 0.3);
        }

        .full-width {
            grid-column: span 2;
        }

        .btn-group {
            display: flex;
            gap: 20px;
            margin-top: 30px;
        }

        .btn {
            flex: 1;
            padding: 18px;
            border-radius: 14px;
            font-size: 18px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.4s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            text-decoration: none;
        }

        .btn-primary {
            background: linear-gradient(135deg, #8b5cf6, #a78bfa);
            color: white;
            border: none;
            box-shadow: 0 10px 30px rgba(139, 92, 246, 0.4);
        }

        .btn-primary:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px rgba(139, 92, 246, 0.5);
            background: linear-gradient(135deg, #7c3aed, #9333ea);
        }

        .btn-secondary {
            background: rgba(255, 255, 255, 0.15);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.3);
            backdrop-filter: blur(8px);
        }

        .btn-secondary:hover {
            background: rgba(255, 255, 255, 0.25);
            transform: translateY(-4px);
        }

        /* Responsive */
        @media (max-width: 640px) {
            .form-grid {
                grid-template-columns: 1fr;
            }
            .full-width {
                grid-column: span 1;
            }
            .btn-group {
                flex-direction: column;
            }
            .header, .form-area {
                padding: 30px 25px;
            }
            .header h1 {
                font-size: 28px;
            }
        }
    </style>
</head>
<body>
    <div class="glass-container">
        <!-- Header -->
        <div class="header">
            <h1>Edit Material</h1>
            <p>Update material details (ID: #<?= $material_id ?>)</p>
        </div>

        <!-- Form Area -->
        <div class="form-area">
            <?php if (!empty($success)): ?>
                <div class="message success">
                    <i class="fas fa-check-circle"></i>
                    <?= htmlspecialchars($success) ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($error)): ?>
                <div class="message error">
                    <i class="fas fa-exclamation-triangle"></i>
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <?php if ($material): ?>
                <form action="edit-material.php?id=<?= $material_id ?>" method="post">
                    <div class="form-grid">
                        <div class="form-group">
                            <label for="sku">
                                SKU <span class="required">*</span>
                            </label>
                            <input type="text" name="sku" id="sku" required maxlength="100"
                                   value="<?= htmlspecialchars($material['sku']) ?>">
                        </div>

                        <div class="form-group">
                            <label for="name">
                                Material Name <span class="required">*</span>
                            </label>
                            <input type="text" name="name" id="name" required
                                   value="<?= htmlspecialchars($material['name']) ?>">
                        </div>

                        <div class="form-group">
                            <label for="category">Category</label>
                            <input type="text" name="category" id="category"
                                   value="<?= htmlspecialchars($material['category'] ?? '') ?>">
                        </div>

                        <div class="form-group">
                            <label for="unit">Unit</label>
                            <input type="text" name="unit" id="unit"
                                   value="<?= htmlspecialchars($material['unit']) ?>">
                        </div>

                        <div class="form-group">
                            <label for="stock">Current Stock</label>
                            <input type="number" name="stock" id="stock" step="0.001" min="0"
                                   value="<?= htmlspecialchars($material['stock']) ?>">
                        </div>

                        <div class="form-group">
                            <label for="reorder_level">Reorder Level</label>
                            <input type="number" name="reorder_level" id="reorder_level" step="0.001" min="0"
                                   value="<?= htmlspecialchars($material['reorder_level']) ?>">
                        </div>

                        <div class="form-group full-width">
                            <label for="last_cost">Last Cost (per unit)</label>
                            <input type="number" name="last_cost" id="last_cost" step="0.01" min="0"
                                   value="<?= htmlspecialchars($material['last_cost']) ?>">
                        </div>
                    </div>

                    <div class="btn-group">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update Material
                        </button>
                        <a href="material-management.php" class="btn btn-secondary">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                    </div>
                </form>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>