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

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

$habitId = intval($_GET['id']);
$message = "";

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

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

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

// 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_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;
    $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 = $habit['image_path'];

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

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

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

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

    <style>
        .form-container {
            width: 700px;
            margin: 0 auto;
            background: #1a1a1f;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #444;
            color: #eee;
        }

        label { margin-top: 10px; display: block; }
        input, select, textarea {
            width: 100%;
            padding: 6px;
            margin-top: 4px;
            background: #222;
            border: 1px solid #444;
            color: #eee;
            border-radius: 4px;
        }

        .habit-img {
            width: 80px;
            height: 80px;
            border-radius: 6px;
            object-fit: cover;
            border: 1px solid #555;
            margin-bottom: 10px;
        }

        .submit-btn {
            margin-top: 15px;
            background: #7a0000;
            border: none;
            padding: 10px 14px;
            color: white;
            cursor: pointer;
            border-radius: 4px;
        }

        .submit-btn:hover {
            background: #a00000;
        }

        .success-message {
            background: #2d662d;
            padding: 10px;
            border-radius: 4px;
            color: #c8ffc8;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>

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

<div class="form-container">

    <h1>Edit Habit</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">
            <option value="daily"       <?= $habit['frequency']=='daily'?'selected':'' ?>>Daily</option>
            <option value="weekly"      <?= $habit['frequency']=='weekly'?'selected':'' ?>>Weekly</option>
            <option value="fortnightly" <?= $habit['frequency']=='fortnightly'?'selected':'' ?>>Fortnightly</option>
            <option value="monthly"     <?= $habit['frequency']=='monthly'?'selected':'' ?>>Monthly</option>
            <option value="one_off"     <?= $habit['frequency']=='one_off'?'selected':'' ?>>One-off</option>
        </select>

        <label>Specific Date (optional)</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>Assign to Tab</label>
        <select name="tab">
            <option value="tab1" <?= $habit['tab']=='tab1'?'selected':'' ?>>TAB1</option>
            <option value="tab2" <?= $habit['tab']=='tab2'?'selected':'' ?>>TAB2</option>
            <option value="tab3" <?= $habit['tab']=='tab3'?'selected':'' ?>>TAB3</option>
            <option value="misc" <?= $habit['tab']=='misc'?'selected':'' ?>>MISC</option>
        </select>

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

        <hr>

        <h3>Linked Item (optional)</h3>

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

        <label>Quantity Consumed Per Completion</label>
        <input type="number" name="consume_amount" min="1" value="<?= htmlspecialchars($habit['consume_amount']) ?>">

        <hr>

        <label>Habit Image</label>
        <?php if ($habit['image_path']): ?>
            <img src="../<?= $habit['image_path'] ?>" class="habit-img">
        <?php endif; ?>
        <input type="file" name="image">

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

    </form>

</div>

</body>
</html>