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

if (!isset($_GET['id'])) {
    die("Habit ID missing.");
}

$id = intval($_GET['id']);

// Fetch habit
$stmt = $pdo->prepare("SELECT * FROM habits WHERE id = ?");
$stmt->execute([$id]);
$habit = $stmt->fetch();

if (!$habit) {
    die("Habit not found.");
}

$message = "";

// Handle update
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_cal    = 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;

    $image_path = $habit['image_path'];

    // Optional new image
    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;
        }
    }

    $update = $pdo->prepare("
        UPDATE habits
        SET title = ?, description = ?, frequency = ?, specific_date = ?, 
            show_on_calendar = ?, is_bounty = ?, xp_reward = ?, image_path = ?
        WHERE id = ?
    ");

    $update->execute([
        $title,
        $description,
        $frequency,
        $specific_date,
        $show_on_cal,
        $is_bounty,
        $xp_reward,
        $image_path,
        $id
    ]);

    $message = "Habit updated successfully.";
    // Refresh habit
    $stmt->execute([$id]);
    $habit = $stmt->fetch();
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Edit Habit</title>
    <link rel="stylesheet" href="../assets/css/style.css">
</head>
<body>

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

<div class="form-container">

    <h1>Edit 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" value="<?= htmlspecialchars($habit['title']) ?>" required>

        <label>Description</label>
        <textarea name="description"><?= htmlspecialchars($habit['description']) ?></textarea>

        <label>Frequency</label>
        <select name="frequency" required>
            <?php
            $freqs = ['daily','weekly','fortnightly','monthly','one_off'];
            foreach ($freqs as $f) {
                $sel = $habit['frequency'] === $f ? "selected" : "";
                echo "<option value='$f' $sel>" . ucfirst($f) . "</option>";
            }
            ?>
        </select>

        <label>Specific Date (for one-offs)</label>
        <input type="date" name="specific_date" value="<?= $habit['specific_date'] ?>">

        <label>XP Reward</label>
        <input type="number" name="xp_reward" min="1" max="500" value="<?= (int)$habit['xp_reward'] ?>">

        <label>
            <input type="checkbox" name="show_on_calendar" <?= $habit['show_on_calendar'] ? 'checked' : '' ?>>
            Show on calendar
        </label>

        <label>
            <input type="checkbox" name="is_bounty" <?= $habit['is_bounty'] ? 'checked' : '' ?>>
            This is a bounty
        </label>

        <label>Habit Image (optional)</label>
        <?php if ($habit['image_path']): ?>
            <div style="margin-bottom:8px;">
                <img src="../<?= $habit['image_path'] ?>" style="width:60px;height:60px;object-fit:cover;">
            </div>
        <?php endif; ?>
        <input type="file" name="image">

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

    </form>

</div>

</body>
</html>