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

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

$product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$product_id) die("Invalid product ID.");

$stmt = $conn->prepare("SELECT * FROM products WHERE id = ?");
$stmt->bind_param("i", $product_id);
$stmt->execute();
$product = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$product) die("Product not found.");

// Fetch categories
$categories = $conn->query("SELECT id, category_name FROM categories ORDER BY category_name");

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_name = trim($_POST['product_name'] ?? '');
    $barcode = trim($_POST['barcode'] ?? '');
    $category_id = $_POST['category_id'] !== '' ? (int)$_POST['category_id'] : null;
    $unit = trim($_POST['unit'] ?? '');
    $cost_price = $_POST['cost_price'] ?? '';
    $selling_price = $_POST['selling_price'] ?? '';
    $vat_rate = $_POST['vat_rate'] ?? '';
    $markup = $_POST['markup'] ?? 30;
    $image_path = $product['image_path'];

    if ($product_name === '') $errors[] = "Product name is required.";
    if ($cost_price === '' || !is_numeric($cost_price) || $cost_price < 0) $errors[] = "Invalid cost price.";
    if ($selling_price === '' || !is_numeric($selling_price) || $selling_price < 0) $errors[] = "Invalid selling price.";
    if ($vat_rate === '' || !is_numeric($vat_rate) || $vat_rate < 0) $errors[] = "Invalid VAT rate.";

    // Loss-selling check
    if (is_numeric($cost_price) && is_numeric($selling_price) && $selling_price < $cost_price) {
        $errors[] = "Selling price cannot be lower than cost price. Loss selling is not allowed.";
    }

    // Image upload
    if (!empty($_FILES['image']['name'])) {
        $allowed = ['image/jpeg', 'image/png', 'image/gif'];
        if (!in_array($_FILES['image']['type'], $allowed)) {
            $errors[] = "Only JPG, PNG, or GIF images allowed.";
        } elseif ($_FILES['image']['size'] > 2 * 1024 * 1024) {
            $errors[] = "Image must be less than 2MB.";
        } else {
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $new_name = uniqid('prod_') . '.' . $ext;
            $dir = __DIR__ . '/../../uploads/products/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $path = $dir . $new_name;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $path)) {
                $image_path = $new_name;
            } else {
                $errors[] = "Failed to upload image.";
            }
        }
    }

    if (!$errors) {
        // Capture old and new values for auditing
        $old_values = $product;
        $new_values = [
            'product_name'   => $product_name,
            'barcode'        => $barcode,
            'category_id'    => $category_id,
            'unit'           => $unit,
            'cost_price'     => $cost_price,
            'selling_price'  => $selling_price,
            'vat_rate'       => $vat_rate,
            'image_path'     => $image_path
        ];

        $stmt = $conn->prepare("UPDATE products SET product_name=?, barcode=?, category_id=?, unit=?, cost_price=?, selling_price=?, vat_rate=?, image_path=?, updated_at=NOW() WHERE id=?");
        $stmt->bind_param("ssisdiddi", $product_name, $barcode, $category_id, $unit, $cost_price, $selling_price, $vat_rate, $image_path, $product_id);
        if ($stmt->execute()) {
            $stmt->close();

            // Insert audit log
            $log_stmt = $conn->prepare("INSERT INTO audit_logs (action_type, table_name, record_id, user_id, old_values, new_values, description) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $action = "update";
            $table = "products";
            $record_id = $product_id;
            $user_id = $_SESSION['user_id'] ?? 0;
            $old_json = json_encode($old_values, JSON_UNESCAPED_UNICODE);
            $new_json = json_encode($new_values, JSON_UNESCAPED_UNICODE);
            $desc = "Product updated via edit_product.php";

            $log_stmt->bind_param("ssiiiss", $action, $table, $record_id, $user_id, $old_json, $new_json, $desc);
            $log_stmt->execute();
            $log_stmt->close();

            header("Location: products.php?msg=Product+updated+successfully");
            exit();
        } else {
            $errors[] = "Database error: " . $stmt->error;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Product</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 {
            margin: 80px auto;
            max-width: 600px;
            padding: 30px 40px;
            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 label { display: block; margin-bottom: 6px; font-weight: bold; }
        form input, form select {
            width: 100%; padding: 10px; margin-bottom: 15px;
            border-radius: 10px; border: none;
            background: rgba(255,255,255,0.15); color: white;
            font-size: 15px;
        }
        .submit-btn {
            width: 100%; padding: 12px;
            background: #ff6f00; border: none;
            border-radius: 25px; color: white;
            font-weight: bold; font-size: 16px;
            cursor: pointer;
        }
        .submit-btn:hover { background: #e65c00; }
        .errors {
            background: #b00020; padding: 10px 15px;
            margin-bottom: 20px; border-radius: 10px;
        }
        .errors ul { margin: 0; padding-left: 18px; }
        img.preview {
            max-width: 100px; max-height: 100px;
            margin-bottom: 10px; border-radius: 10px;
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <h2>Edit Product</h2>

    <?php if ($errors): ?>
        <div class="errors"><ul>
            <?php foreach ($errors as $error): ?>
                <li><?= htmlspecialchars($error) ?></li>
            <?php endforeach; ?>
        </ul></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data" onsubmit="return validateSellingPrice();">
        <label for="product_name">Product Name *</label>
        <input type="text" id="product_name" name="product_name" required value="<?= htmlspecialchars($_POST['product_name'] ?? $product['product_name']) ?>">

        <label for="barcode">Barcode</label>
        <input type="text" id="barcode" name="barcode" value="<?= htmlspecialchars($_POST['barcode'] ?? $product['barcode']) ?>">

        <label for="category_id">Category</label>
        <select name="category_id" id="category_id">
            <option value="">-- Select Category --</option>
            <?php while ($cat = $categories->fetch_assoc()): ?>
                <option value="<?= $cat['id'] ?>" <?= ($cat['id'] == ($product['category_id'] ?? '')) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($cat['category_name']) ?>
                </option>
            <?php endwhile; ?>
        </select>

        <label for="unit">Unit</label>
        <input type="text" id="unit" name="unit" value="<?= htmlspecialchars($_POST['unit'] ?? $product['unit']) ?>">

        <label for="cost_price">Cost Price *</label>
        <input type="number" step="0.01" min="0" id="cost_price" name="cost_price" required value="<?= htmlspecialchars($_POST['cost_price'] ?? $product['cost_price']) ?>" onchange="suggestSellingPrice()">

        <label for="markup">Markup (%)</label>
        <input type="number" step="0.01" min="0" id="markup" name="markup" value="<?= htmlspecialchars($_POST['markup'] ?? 30) ?>" onchange="suggestSellingPrice()">

        <label for="selling_price">Selling Price *</label>
        <input type="number" step="0.01" min="0" id="selling_price" name="selling_price" required value="<?= htmlspecialchars($_POST['selling_price'] ?? $product['selling_price']) ?>">

        <label for="vat_rate">VAT Rate (%) *</label>
        <input type="number" step="0.01" min="0" id="vat_rate" name="vat_rate" required value="<?= htmlspecialchars($_POST['vat_rate'] ?? $product['vat_rate']) ?>">

        <?php if ($product['image_path']): ?>
            <label>Current Image:</label>
            <img src="../../uploads/products/<?= $product['image_path'] ?>" alt="Product Image" class="preview">
        <?php endif; ?>

        <label for="image">Replace Image</label>
        <input type="file" id="image" name="image" accept="image/*">

        <button type="submit" class="submit-btn">Update Product</button>
    </form>
</div>

<script>
function validateSellingPrice() {
    const cost = parseFloat(document.getElementById('cost_price').value);
    const sell = parseFloat(document.getElementById('selling_price').value);
    if (sell < cost) {
        alert("❌ Selling price must not be less than cost price. This would be a loss.");
        return false;
    }
    return true;
}

function suggestSellingPrice() {
    const cost = parseFloat(document.getElementById('cost_price').value);
    const markup = parseFloat(document.getElementById('markup').value);
    if (!isNaN(cost) && !isNaN(markup)) {
        const suggested = (cost * (1 + markup / 100)).toFixed(2);
        document.getElementById('selling_price').placeholder = "Suggested: " + suggested;
    }
}
</script>
</body>
</html>
