<?php
session_start();
if (!isset($_SESSION['role_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');

// === Audit log helper ===
function logAudit($conn, $action, $details, $module = 'categories') {
    $user_id = $_SESSION['user_id'] ?? null;
    $role_id = $_SESSION['role_id'] ?? null;
    $device_info = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $details_json = json_encode($details);
    $stmt = $conn->prepare("INSERT INTO audit_log (user_id, role_id, action, details, module, created_at, device_info)
                            VALUES (?, ?, ?, ?, ?, NOW(), ?)");
    $stmt->bind_param("iissss", $user_id, $role_id, $action, $details_json, $module, $device_info);
    $stmt->execute();
    $stmt->close();
}

// === Validate ID ===
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: categories.php?msg=Invalid+Category+ID");
    exit();
}

$category_id = (int)$_GET['id'];

// === Fetch Category ===
$stmt = $conn->prepare("SELECT * FROM categories WHERE id = ?");
$stmt->bind_param("i", $category_id);
$stmt->execute();
$result = $stmt->get_result();
$category = $result->fetch_assoc();
$stmt->close();

if (!$category) {
    header("Location: categories.php?msg=Category+not+found");
    exit();
}

// === Handle Update ===
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['category_name']);
    $desc = trim($_POST['description']);

    if ($name !== '') {
        $update = $conn->prepare("UPDATE categories SET category_name = ?, description = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
        $update->bind_param("ssi", $name, $desc, $category_id);
        if ($update->execute()) {
            // Log audit
            logAudit($conn, 'update', [
                'category_id' => $category_id,
                'old_name' => $category['category_name'],
                'new_name' => $name,
                'old_description' => $category['description'],
                'new_description' => $desc
            ]);
            header("Location: categories.php?success=Category+updated");
            exit();
        }
        $update->close();
    } else {
        header("Location: categories.php?error=Category+name+is+required");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Category - Digital POS</title>
    <link rel="stylesheet" href="../../css/dashboard.css">
    <style>
        body, html {
            margin: 0; padding: 0;
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/bg.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
        }
        .overlay {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.6);
            z-index: -1;
        }
        .content {
            max-width: 600px;
            margin: 100px auto;
            padding: 30px;
            background: rgba(255, 255, 255, 0.08);
            border-radius: 20px;
            backdrop-filter: blur(15px);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
        }
        h2 {
            text-align: center;
            margin-bottom: 25px;
        }
        form input, form textarea {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 10px;
            border: none;
            background: rgba(255, 255, 255, 0.15);
            color: white;
        }
        form input::placeholder, textarea::placeholder {
            color: rgba(255, 255, 255, 0.6);
        }
        button {
            padding: 12px 20px;
            background: #ff6f00;
            color: white;
            border: none;
            border-radius: 10px;
            font-weight: bold;
            cursor: pointer;
        }
        button:hover {
            background: #e65c00;
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <h2>Edit Category</h2>
    <form method="POST">
        <input type="text" name="category_name" required value="<?= htmlspecialchars($category['category_name']) ?>" placeholder="Category name">
        <textarea name="description" rows="3" placeholder="Description"><?= htmlspecialchars($category['description']) ?></textarea>
        <button type="submit">Update Category</button>
    </form>
</div>
</body>
</html>
