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

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

$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];
$success = false;

// Audit log helper
function log_audit($conn, $user_id, $role_id, $action, $details, $module) {
    $device_info = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown Device';
    $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, $module, $device_info);
    $stmt->execute();
    $stmt->close();
}

$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'] ?? '');
    $markup = $_POST['markup'] ?? 30;
    $cost_price = $_POST['cost_price'] ?? '';
    $selling_price = $_POST['selling_price'] ?? '';
    $vat_rate = $_POST['vat_rate'] ?? '';
    $image_path = null;

    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 ($selling_price < $cost_price) $errors[] = "Selling price cannot be lower than cost price. Loss selling is not allowed.";

    // Check for duplicates
    $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.";
    }
    $check->close();

    // Image upload
    if (!empty($_FILES['image']['name'])) {
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $file_type = $_FILES['image']['type'];
        $file_size = $_FILES['image']['size'];
        $tmp_name = $_FILES['image']['tmp_name'];

        if (!in_array($file_type, $allowed_types)) {
            $errors[] = "Image must be JPG, PNG, or GIF.";
        } elseif ($file_size > 2 * 1024 * 1024) {
            $errors[] = "Image must be under 2MB.";
        } else {
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $new_filename = uniqid('prod_') . '.' . $ext;
            $upload_dir = __DIR__ . '/../../uploads/products/';
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            if (move_uploaded_file($tmp_name, $upload_dir . $new_filename)) {
                $image_path = $new_filename;
            } else {
                $errors[] = "Failed to upload image.";
            }
        }
    }

    if (empty($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();

            $log_data = [
                'product_id'    => $product_id,
                'product_name'  => $product_name,
                'barcode'       => $barcode,
                'category_id'   => $category_id,
                'unit'          => $unit,
                'image_path'    => $image_path
            ];
            $details = "Manager added product:\n" . json_encode($log_data, JSON_PRETTY_PRINT);
            log_audit($conn, $user_id, $role_id, 'Add', $details, 'Products');

            $success = true;
            echo "<script>
                setTimeout(() => {
                    window.location.href = 'products.php?msg=Product+added+successfully';
                }, 2000);
            </script>";
        } else {
            $errors[] = "Database error: " . $stmt->error;
        }
    }
}
?>

<!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;
        }
        form input::placeholder {
            color: rgba(255,255,255,0.6);
        }
        .submit-btn {
            width: 100%;
            padding: 12px;
            background: #ff6f00;
            border: none;
            border-radius: 25px;
            color: white;
            font-weight: bold;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }
        .submit-btn:hover {
            background: #e65c00;
        }
        .errors {
            background: #b00020;
            padding: 10px 15px;
            margin-bottom: 20px;
            border-radius: 10px;
        }
        .success {
            background: #2e7d32;
            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; ?>

    <?php if ($success): ?>
        <div class="success">
            ✅ Product added successfully! Redirecting to product list...
        </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'] ?? '') ?>" placeholder="Enter product name">

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

        <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>
