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

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

$errors = [];
$success = false;

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 = null;

    // Validation
    if ($product_name === '') $errors[] = "Product name is required.";
    if ($cost_price === '' || !is_numeric($cost_price) || $cost_price < 0) $errors[] = "Cost price must be non-negative.";
    if ($selling_price === '' || !is_numeric($selling_price) || $selling_price < 0) $errors[] = "Selling price must be non-negative.";
    if ($vat_rate === '' || !is_numeric($vat_rate) || $vat_rate < 0) $errors[] = "VAT rate must be non-negative.";
    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.";
    }

    // Duplicate check
    $check = $conn->prepare("SELECT id FROM products WHERE product_name = ? OR barcode = ?");
    $check->bind_param("ss", $product_name, $barcode);
    $check->execute();
    $check->store_result();
    if ($check->num_rows > 0) {
        $errors[] = "❌ A product with the same name or barcode already exists. Please use a unique name/barcode.";
    }
    $check->close();

    // 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) {
        $stmt = $conn->prepare("INSERT INTO products (product_name, barcode, category_id, unit, cost_price, selling_price, vat_rate, image_path, created_at, updated_at)
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");
        $stmt->bind_param("ssisdidd", $product_name, $barcode, $category_id, $unit, $cost_price, $selling_price, $vat_rate, $image_path);

        if ($stmt->execute()) {
            $product_id = $stmt->insert_id;
            $stmt->close();

            // Audit log entry
            $action_type = 'create';
            $table_name = 'products';
            $record_id = $product_id;
            $user_id = $_SESSION['user_id'];
            $store_id = $_SESSION['store_id'] ?? null;
            $description = 'New product created by Admin';
            $old_values = null;
            $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
            ];
            $old_json = null;
            $new_json = json_encode($new_values, JSON_UNESCAPED_UNICODE);

            $log_stmt = $conn->prepare("INSERT INTO audit_logs (action_type, table_name, record_id, user_id, old_values, new_values, description, store_id, created_at)
                                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $log_stmt->bind_param("ssiiisss", $action_type, $table_name, $record_id, $user_id, $old_json, $new_json, $description, $store_id);
            $log_stmt->execute();
            $log_stmt->close();

            header("Location: products.php?msg=Product+added+successfully");
            exit();
        } else {
            $errors[] = "Database error: " . $stmt->error;
        }
    }
}

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

<!-- HTML STARTS -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Add Product - 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/profile.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: 0 auto;
            max-width: 600px;
            padding: 10px 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: black;
            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; }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <h2>Add New 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'] ?? '') ?>">

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

        <label for="category_id">Category</label>
        <select id="category_id" name="category_id">
            <option value="">-- Select Category --</option>
            <?php while ($cat = $categories->fetch_assoc()): ?>
                <option value="<?= $cat['id'] ?>" <?= (isset($_POST['category_id']) && $_POST['category_id'] == $cat['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'] ?? '') ?>" placeholder="e.g., pcs, kg, liter">

        <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'] ?? '') ?>" 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'] ?? '') ?>">

        <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'] ?? '') ?>">

        <label for="image">Product Image (optional)</label>
        <input type="file" id="image" name="image" accept="image/*">

        <button type="submit" class="submit-btn">Add 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.");
        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>
