<?php
/**
 * Preaching Plan - add/edit form
 */

// Ensure preaching_plan table exists (safety check)
if (isset($pdo)) {
    try {
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS preaching_plan (
                id INT AUTO_INCREMENT PRIMARY KEY,
                service_date DATE NOT NULL,
                service_type VARCHAR(20) DEFAULT 'first-service',
                occasion VARCHAR(200),
                preacher VARCHAR(200),
                liturgist VARCHAR(200),
                ga_bible_reader VARCHAR(200),
                twi_bible_reader VARCHAR(200),
                english_bible_reader VARCHAR(200),
                remarks VARCHAR(200),
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX idx_service_date (service_date),
                INDEX idx_service_type (service_type)
            )
        ");
        
        // Add english_bible_reader column if it doesn't exist (for existing tables)
        try {
            $pdo->exec("ALTER TABLE preaching_plan ADD COLUMN english_bible_reader VARCHAR(200) AFTER twi_bible_reader");
        } catch (PDOException $e) {
            // Column already exists, ignore
            if (strpos($e->getMessage(), 'Duplicate column name') === false) {
                error_log('Preaching plan column addition (form): ' . $e->getMessage());
            }
        }
        
        // Add "applies to all services" columns if they don't exist
        $applyAllColumns = [
            'preacher_applies_all' => 'AFTER preacher',
            'liturgist_applies_all' => 'AFTER liturgist',
            'ga_reader_applies_all' => 'AFTER ga_bible_reader',
            'twi_reader_applies_all' => 'AFTER twi_bible_reader',
            'english_reader_applies_all' => 'AFTER english_bible_reader'
        ];
        
        foreach ($applyAllColumns as $colName => $position) {
            try {
                $pdo->exec("ALTER TABLE preaching_plan ADD COLUMN $colName TINYINT(1) DEFAULT 0 $position");
            } catch (PDOException $e) {
                // Column already exists, ignore
                if (strpos($e->getMessage(), 'Duplicate column name') === false) {
                    error_log("Preaching plan column addition ($colName): " . $e->getMessage());
                }
            }
        }
    } catch (PDOException $e) {
        error_log('Preaching plan table creation (form): ' . $e->getMessage());
    }
}

// Ensure we have the required variables from parent scope
if (!isset($action)) {
    $action = $route_action ?? 'add';
}
if (!isset($id)) {
    $id = isset($route_id) ? (int)$route_id : null;
}

$isEdit = ($action === 'edit' && $id);
$entry = null;
$errors = [];

if ($isEdit) {
    $stmt = $pdo->prepare('SELECT * FROM preaching_plan WHERE id = ?');
    $stmt->execute([$id]);
    $entry = $stmt->fetch();
    if (!$entry) {
        header('Location: ' . BASE_PATH . '/events/preaching-plan');
        exit;
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $service_date = trim($_POST['service_date'] ?? '');
    $service_type = trim($_POST['service_type'] ?? 'first-service');
    $occasion = trim($_POST['occasion'] ?? '');
    $preacher = trim($_POST['preacher'] ?? '');
    $liturgist = trim($_POST['liturgist'] ?? '');
    $ga_bible_reader = trim($_POST['ga_bible_reader'] ?? '');
    $twi_bible_reader = trim($_POST['twi_bible_reader'] ?? '');
    $english_bible_reader = trim($_POST['english_bible_reader'] ?? '');
    $remarks = trim($_POST['remarks'] ?? '');

    if (empty($service_date)) {
        $errors[] = 'Service date is required.';
    }

    if (empty($errors)) {
        try {
            if ($isEdit) {
                $stmt = $pdo->prepare('UPDATE preaching_plan SET service_date=?, service_type=?, occasion=?, preacher=?, liturgist=?, ga_bible_reader=?, twi_bible_reader=?, english_bible_reader=?, remarks=? WHERE id=?');
                $stmt->execute([$service_date, $service_type, $occasion, $preacher, $liturgist, $ga_bible_reader, $twi_bible_reader, $english_bible_reader, $remarks, $id]);
            } else {
                $stmt = $pdo->prepare('INSERT INTO preaching_plan (service_date, service_type, occasion, preacher, liturgist, ga_bible_reader, twi_bible_reader, english_bible_reader, remarks) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
                $stmt->execute([$service_date, $service_type, $occasion, $preacher, $liturgist, $ga_bible_reader, $twi_bible_reader, $english_bible_reader, $remarks]);
            }
            header('Location: ' . BASE_PATH . '/events/preaching-plan?toast=' . urlencode('Entry saved successfully.'));
            exit;
        } catch (PDOException $e) {
            // Check if error is due to missing column
            if (strpos($e->getMessage(), 'english_bible_reader') !== false || strpos($e->getMessage(), "doesn't exist") !== false) {
                // Try to add the column and retry
                try {
                    $pdo->exec("ALTER TABLE preaching_plan ADD COLUMN english_bible_reader VARCHAR(200) AFTER twi_bible_reader");
                    // Retry the insert/update
                    if ($isEdit) {
                        $stmt = $pdo->prepare('UPDATE preaching_plan SET service_date=?, service_type=?, occasion=?, preacher=?, liturgist=?, ga_bible_reader=?, twi_bible_reader=?, english_bible_reader=?, remarks=? WHERE id=?');
                        $stmt->execute([$service_date, $service_type, $occasion, $preacher, $liturgist, $ga_bible_reader, $twi_bible_reader, $english_bible_reader, $remarks, $id]);
                    } else {
                        $stmt = $pdo->prepare('INSERT INTO preaching_plan (service_date, service_type, occasion, preacher, liturgist, ga_bible_reader, twi_bible_reader, english_bible_reader, remarks) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
                        $stmt->execute([$service_date, $service_type, $occasion, $preacher, $liturgist, $ga_bible_reader, $twi_bible_reader, $english_bible_reader, $remarks]);
                    }
                    // Redirect back with filters preserved
                    $redirectUrl = BASE_PATH . '/events/preaching-plan?toast=' . urlencode('Entry saved successfully.');
                    $redirectUrl .= '&year=' . date('Y', strtotime($service_date));
                    $redirectUrl .= '&service_type=' . urlencode($service_type);
                    header('Location: ' . $redirectUrl);
                    exit;
                } catch (PDOException $e2) {
                    $errors[] = 'Error saving entry: ' . $e2->getMessage();
                    error_log('Preaching plan save error (retry): ' . $e2->getMessage());
                }
            } else {
                $errors[] = 'Error saving entry: ' . $e->getMessage();
                error_log('Preaching plan save error: ' . $e->getMessage());
            }
        }
    }

    $entry = [
        'service_date' => $service_date,
        'service_type' => $service_type,
        'occasion' => $occasion,
        'preacher' => $preacher,
        'liturgist' => $liturgist,
        'ga_bible_reader' => $ga_bible_reader,
        'twi_bible_reader' => $twi_bible_reader,
        'english_bible_reader' => $english_bible_reader,
        'remarks' => $remarks,
    ];
}

$pageTitle = $isEdit ? 'Edit Preaching Plan Entry' : 'Add Preaching Plan Entry';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="header">
    <h1><?= $isEdit ? 'Edit Preaching Plan Entry' : 'Add Preaching Plan Entry' ?></h1>
    <div class="header-actions">
        <a href="<?= BASE_PATH ?>/events/preaching-plan">Back to Preaching Plan</a>
        <a href="<?= BASE_PATH ?>/logout">Logout</a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-bottom: 1rem; padding: 0.75rem; background-color: #fee; border: 1px solid #fcc; color: #c00; border-radius: 4px;">
        <?php foreach ($errors as $error): ?>
            <div><?= htmlspecialchars($error) ?></div>
        <?php endforeach; ?>
    </div>
    <div data-toast="error" data-toast-msg="<?= htmlspecialchars(implode(' ', $errors)) ?>" style="display:none"></div>
<?php endif; ?>

<div style="display: flex; justify-content: center; margin-bottom: 2rem;">
    <div class="card" style="max-width: 600px; width: 100%;">
        <form method="post">
        <div class="form-group">
            <label for="service_date">Service Date *</label>
            <input type="date" id="service_date" name="service_date" required
                value="<?= htmlspecialchars($entry['service_date'] ?? date('Y-m-d')) ?>">
        </div>
        <div class="form-group">
            <label for="service_type">Service Type *</label>
            <select id="service_type" name="service_type" required>
                <option value="first-service" <?= ($entry['service_type'] ?? 'first-service') === 'first-service' ? 'selected' : '' ?>>First Service</option>
                <option value="forenoon" <?= ($entry['service_type'] ?? '') === 'forenoon' ? 'selected' : '' ?>>Forenoon</option>
                <option value="joint-service" <?= ($entry['service_type'] ?? '') === 'joint-service' ? 'selected' : '' ?>>Joint Service</option>
            </select>
        </div>
        <div class="form-group">
            <label for="occasion">Occasion</label>
            <input type="text" id="occasion" name="occasion"
                value="<?= htmlspecialchars($entry['occasion'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="preacher">Preacher</label>
            <input type="text" id="preacher" name="preacher"
                value="<?= htmlspecialchars($entry['preacher'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="liturgist">Liturgist</label>
            <input type="text" id="liturgist" name="liturgist"
                value="<?= htmlspecialchars($entry['liturgist'] ?? '') ?>">
        </div>
        <div class="form-group" id="ga_reader_group" style="<?= ($entry['service_type'] ?? 'first-service') === 'first-service' ? 'display: none;' : '' ?>">
            <label for="ga_bible_reader">Ga Bible Reader</label>
            <input type="text" id="ga_bible_reader" name="ga_bible_reader"
                value="<?= htmlspecialchars($entry['ga_bible_reader'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="twi_bible_reader">Twi Bible Reader</label>
            <input type="text" id="twi_bible_reader" name="twi_bible_reader"
                value="<?= htmlspecialchars($entry['twi_bible_reader'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="english_bible_reader">English Bible Reader</label>
            <input type="text" id="english_bible_reader" name="english_bible_reader"
                value="<?= htmlspecialchars($entry['english_bible_reader'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label for="remarks">Remarks</label>
            <input type="text" id="remarks" name="remarks"
                value="<?= htmlspecialchars($entry['remarks'] ?? '') ?>">
        </div>
        <button type="submit" class="btn"><?= $isEdit ? 'Update' : 'Add' ?> Entry</button>
        <a href="<?= BASE_PATH ?>/events/preaching-plan" class="btn btn-secondary">Cancel</a>
    </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const serviceTypeSelect = document.getElementById('service_type');
    const gaReaderGroup = document.getElementById('ga_reader_group');
    
    if (serviceTypeSelect && gaReaderGroup) {
        function toggleGaReader() {
            if (serviceTypeSelect.value === 'first-service') {
                gaReaderGroup.style.display = 'none';
                document.getElementById('ga_bible_reader').value = '';
            } else {
                gaReaderGroup.style.display = 'block';
            }
        }
        
        serviceTypeSelect.addEventListener('change', toggleGaReader);
        toggleGaReader(); // Run on page load
    }
});
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
