<?php
require_once "../includes/config.php";

$message = "";

// Fetch items for linking (optional consumption)
$itemStmt = $pdo->query("
    SELECT id, title, quantity, quantity_max
    FROM items
    ORDER BY title ASC
");
$items = $itemStmt->fetchAll();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $title            = $_POST['title'];
    $description      = $_POST['description'];
    $frequency        = $_POST['frequency'];
    $specific_date    = !empty($_POST['specific_date']) ? $_POST['specific_date'] : null;
    $show_on_calendar = isset($_POST['show_on_calendar']) ? 1 : 0;
    $is_bounty        = isset($_POST['is_bounty']) ? 1 : 0;
    $xp_reward        = !empty($_POST['xp_reward']) ? intval($_POST['xp_reward']) : 10;

    // Inventory tab assignment
    $tab = $_POST['tab'] ?? 'misc';

    // Optional linked item
    $linked_item_id = !empty($_POST['linked_item_id']) ? intval($_POST['linked_item_id']) : null;
    $consume_amount = !empty($_POST['consume_amount']) ? intval($_POST['consume_amount']) : null;

    // Handle image upload
    $image_path = null;

    if (!empty($_FILES['image']['name'])) {
        $uploadDir = HABIT_IMAGES_PATH;
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $filename   = time() . "_" . basename($_FILES['image']['name']);
        $targetPath = $uploadDir . $filename;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $targetPath)) {
            $image_path = "assets/images/habits/" . $filename;
        }
    }

    // Insert habit
    $stmt = $pdo->prepare("
        INSERT INTO habits 
        (title, description, image_path, frequency, specific_date, show_on_calendar, is_bounty, xp_reward, tab, linked_item_id, consume_amount)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->execute([
        $title,
        $description,
        $image_path,
        $frequency,
        $specific_date,
        $show_on_calendar,
        $is_bounty,
        $xp_reward,
        $tab,
        $linked_item_id,
        $consume_amount
    ]);

    $message = "Habit/Bounty successfully created!";
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Create Habit</title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>

<?php include "../includes/menu.php"; ?>

<div class="form-container">

    <h1>Create New Habit / Bounty</h1>

    <?php if ($message): ?>
        <div class="success-message"><?= $message ?></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">

        <label>Title</label>
        <input type="text" name="title" required>

        <label>Description</label>
        <textarea name="description"></textarea>

        <label>Frequency</label>
        <select name="frequency" required>
            <option value="daily">Daily</option>
            <option value="weekly">Weekly</option>
            <option value="fortnightly">Fortnightly</option>
            <option value="monthly">Monthly</option>
            <option value="one_off">One-off</option>
        </select>

        <label>Specific Date (optional for one-offs)</label>
        <input type="date" name="specific_date">

        <label>XP Reward</label>
        <input type="number" name="xp_reward" min="1" max="500" value="10">

        <label>Assign to Inventory Tab</label>
        <select name="tab">
            <option value="tab1">TAB1</option>
            <option value="tab2">TAB2</option>
            <option value="tab3">TAB3</option>
            <option value="misc">MISC</option>
        </select>

        <label>
            <input type="checkbox" name="show_on_calendar" checked>
            Show on calendar
        </label>

        <label>
            <input type="checkbox" name="is_bounty">
            This is a bounty
        </label>

        <hr>

        <h3>Optional: Link to an Item (for consumption)</h3>

        <label>Linked Item</label>
        <select name="linked_item_id">
            <option value="">-- None --</option>
            <?php foreach ($items as $item): ?>
                <option value="<?= $item['id'] ?>">
                    <?= htmlspecialchars($item['title']) ?>
                </option>
            <?php endforeach; ?>
        </select>

        <label>Quantity Consumed Per Completion</label>
        <input type="number" name="consume_amount" min="1" placeholder="Leave blank if none">

        <hr>

        <label>Habit Image (optional)</label>
        <input type="file" name="image">

        <button type="submit" class="submit-btn">Save Habit</button>

    </form>

</div>

</body>
</html>