<?php
require_once "../includes/db.php";
require_once "../includes/functions.php";

$message = "";

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

    // Handle image upload
    $image_path = null;

    if (!empty($_FILES['image']['name'])) {
        $uploadDir = "../assets/images/habits/";
        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 into database
    $stmt = $pdo->prepare("
        INSERT INTO habits (title, description, image_path, frequency, specific_date, show_on_calendar, is_bounty)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");

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

    $message = "Habit/Bounty successfully created!";
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Create Habit</title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>

<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>
            <input type="checkbox" name="show_on_calendar" checked>
            Show on calendar
        </label>

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

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

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

    </form>

</div>

</body>
</html>