<?php
session_start();

require_once __DIR__ . '/../../includes/helpers.php';
require_once __DIR__ . '/../../includes/layout.php';
require_once __DIR__ . '/../../includes/expense_shell.php';

if (!isset($_SESSION['authenticated'])) {
    redirect(page_url('signin'));
}

function trip_normalize_date(string $value): ?string
{
    $value = trim($value);
    if ($value === '') {
        return null;
    }

    $formats = ['Y-m-d', 'd/m/Y', 'd-m-Y'];
    foreach ($formats as $format) {
        $date = DateTime::createFromFormat($format, $value);
        if ($date instanceof DateTime) {
            return $date->format('Y-m-d');
        }
    }

    $timestamp = strtotime($value);
    return $timestamp ? date('Y-m-d', $timestamp) : null;
}

function trip_date_display(?string $value): string
{
    $value = trim((string) $value);
    if ($value === '') {
        return 'Not set';
    }

    $date = DateTime::createFromFormat('Y-m-d', $value);
    return $date instanceof DateTime ? $date->format('d M Y') : $value;
}

function trip_ensure_cover_column(): void
{
    $exists = fetch_one(
        'SELECT 1
         FROM information_schema.columns
         WHERE table_schema = DATABASE()
           AND table_name = ?
           AND column_name = ?
         LIMIT 1',
        'ss',
        ['expense_trips', 'cover_image_path']
    );

    if (!$exists) {
        db()->query('ALTER TABLE expense_trips ADD COLUMN cover_image_path VARCHAR(255) NOT NULL DEFAULT "" AFTER end_date');
    }
}

function trip_store_cover(array $file, int $userId): string
{
    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK || empty($file['tmp_name'])) {
        return '';
    }

    $allowedExt = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $originalName = (string) ($file['name'] ?? '');
    $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
    if (!in_array($extension, $allowedExt, true)) {
        return '';
    }

    $uploadDir = __DIR__ . '/../../images/trips';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    $fileName = 'trip_cover_' . $userId . '_' . time() . '.' . $extension;
    $targetPath = $uploadDir . '/' . $fileName;

    if (!move_uploaded_file((string) $file['tmp_name'], $targetPath)) {
        return '';
    }

    return 'images/trips/' . $fileName;
}

function trip_cover_url(string $path): string
{
    $path = trim($path);
    if ($path === '') {
        return asset_url('images/img1.jpg');
    }

    if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://') || str_starts_with($path, '../') || str_starts_with($path, '/')) {
        return $path;
    }

    return asset_url($path);
}

$userId = current_user_id();
if ($userId <= 0) {
    redirect(page_url('signin'));
}

$tripSuccess = flash('trip_success');
$tripError = flash('trip_error');
$createdTripId = (int) ($_GET['created'] ?? 0);

trip_ensure_cover_column();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tripName = trim((string) ($_POST['trip_name'] ?? ''));
    $travelType = strtolower(trim((string) ($_POST['travel_type'] ?? 'domestic')));
    $businessPurpose = trim((string) ($_POST['business_purpose'] ?? ''));
    $destination = trim((string) ($_POST['destination'] ?? ''));
    $startDate = trip_normalize_date((string) ($_POST['start_date'] ?? ''));
    $endDate = trip_normalize_date((string) ($_POST['end_date'] ?? ''));
    $status = trim((string) ($_POST['status'] ?? 'planned'));

    if (!in_array($travelType, ['domestic', 'international'], true)) {
        $travelType = 'domestic';
    }

    if (!in_array($status, ['planned', 'active', 'completed', 'archived'], true)) {
        $status = 'planned';
    }

    $errors = [];
    if ($tripName === '') {
        $errors[] = 'Trip name is required.';
    }

    if ($travelType === 'international' && $destination === '') {
        $errors[] = 'Destination is required for international trips.';
    }

    if ($startDate !== null && $endDate !== null && $endDate < $startDate) {
        $errors[] = 'End date cannot be earlier than the start date.';
    }

    if ($errors !== []) {
        $_SESSION['old'] = [
            'trip_name' => $tripName,
            'travel_type' => $travelType,
            'business_purpose' => $businessPurpose,
            'destination' => $destination,
            'start_date' => (string) ($_POST['start_date'] ?? ''),
            'end_date' => (string) ($_POST['end_date'] ?? ''),
            'status' => $status,
        ];
        flash('trip_error', implode(' ', $errors));
        redirect(route_url('trips/new/'));
    }

    $coverImagePath = trip_store_cover($_FILES['trip_cover'] ?? [], $userId);

    $insertId = execute_query(
        'INSERT INTO expense_trips (user_id, trip_name, travel_type, business_purpose, destination, status, start_date, end_date, cover_image_path)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
        'issssssss',
        [
            $userId,
            $tripName,
            $travelType,
            $businessPurpose,
            $destination,
            $status,
            $startDate,
            $endDate,
            $coverImagePath,
        ]
    );

    if ($insertId > 0) {
        $_SESSION['old'] = [];
        flash('trip_success', 'Trip created successfully.');
        redirect(page_url('trips', 'created=' . $insertId));
    }

    $_SESSION['old'] = [
        'trip_name' => $tripName,
        'travel_type' => $travelType,
        'business_purpose' => $businessPurpose,
        'destination' => $destination,
        'start_date' => (string) ($_POST['start_date'] ?? ''),
        'end_date' => (string) ($_POST['end_date'] ?? ''),
        'status' => $status,
    ];
    flash('trip_error', 'We could not save the trip right now. Please try again.');
    redirect(route_url('trips/new/'));
}

$createdTrip = null;
if ($createdTripId > 0) {
    $createdTrip = fetch_one(
        'SELECT id, trip_name, travel_type, business_purpose, destination, status, start_date, end_date, cover_image_path
         FROM expense_trips
         WHERE id = ? AND user_id = ?
         LIMIT 1',
        'ii',
        [$createdTripId, $userId]
    );
}

$formTrip = [
    'trip_name' => old('trip_name', (string) ($createdTrip['trip_name'] ?? '')),
    'travel_type' => old('travel_type', (string) ($createdTrip['travel_type'] ?? 'domestic')),
    'business_purpose' => old('business_purpose', (string) ($createdTrip['business_purpose'] ?? '')),
    'destination' => old('destination', (string) ($createdTrip['destination'] ?? '')),
    'start_date' => old('start_date', (string) ($createdTrip['start_date'] ?? '')),
    'end_date' => old('end_date', (string) ($createdTrip['end_date'] ?? '')),
    'status' => old('status', (string) ($createdTrip['status'] ?? 'planned')),
];

$previewTripName = trim($formTrip['trip_name']) !== '' ? trim($formTrip['trip_name']) : 'New Trip';
$previewTravelType = strtolower(trim($formTrip['travel_type'])) === 'international' ? 'International' : 'Domestic';
$previewDestination = trim($formTrip['destination']) !== '' ? trim($formTrip['destination']) : 'Destination pending';
$previewPurpose = trim($formTrip['business_purpose']) !== '' ? trim($formTrip['business_purpose']) : 'Business purpose not set yet';
$previewStatus = ucfirst(trim($formTrip['status']) !== '' ? trim($formTrip['status']) : 'planned');
$previewStart = trip_date_display($formTrip['start_date'] !== '' ? $formTrip['start_date'] : null);
$previewEnd = trip_date_display($formTrip['end_date'] !== '' ? $formTrip['end_date'] : null);
$previewCoverPath = trim((string) ($createdTrip['cover_image_path'] ?? ''));
$previewDateRange = ($previewStart === 'Not set' && $previewEnd === 'Not set') ? 'Not set' : $previewStart . ' - ' . $previewEnd;

render_expense_shell_start('New Trip | Expense', 'dashboard-page trip-page', 'trips');
?>
<div class="page-surface trip-create-surface">
    <div class="trip-create-shell">
        <section class="trip-create-panel panel">
            <header class="trip-create-header">
                <div>
                    <p class="trip-create-kicker">Trips</p>
                    <h1>Get started with Trips</h1>
                    <p class="trip-create-copy">
                        Create a trip request, attach a trip image, and keep the request ready for linked reports and advances.
                    </p>
                </div>

                <a class="page-close-button" href="<?= e(page_url('trips')) ?>" aria-label="Close">
                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                </a>
            </header>

            <?php if ($tripSuccess !== null): ?>
                <div class="trip-banner trip-banner--success"><?= e($tripSuccess) ?></div>
            <?php endif; ?>

            <?php if ($tripError !== null): ?>
                <div class="trip-banner trip-banner--error"><?= e($tripError) ?></div>
            <?php endif; ?>

            <form class="trip-create-form" method="post" enctype="multipart/form-data" data-trip-create-form>
                <div class="trip-create-grid">
                    <label class="trip-form-field">
                        <span>Trip Name *</span>
                        <input type="text" name="trip_name" value="<?= e($formTrip['trip_name']) ?>" placeholder="eg: Trip to New York" data-trip-name>
                    </label>

                    <label class="trip-form-field">
                        <span>Status</span>
                        <select name="status" data-trip-status>
                            <option value="planned"<?= $formTrip['status'] === 'planned' ? ' selected' : '' ?>>Planned</option>
                            <option value="active"<?= $formTrip['status'] === 'active' ? ' selected' : '' ?>>Active</option>
                            <option value="completed"<?= $formTrip['status'] === 'completed' ? ' selected' : '' ?>>Completed</option>
                            <option value="archived"<?= $formTrip['status'] === 'archived' ? ' selected' : '' ?>>Archived</option>
                        </select>
                    </label>

                    <label class="trip-form-field trip-form-field--wide" data-trip-destination-field>
                        <span>Destination</span>
                        <input type="text" name="destination" value="<?= e($formTrip['destination']) ?>" placeholder="City, state or country" data-trip-destination>
                        <small data-trip-destination-hint>Enter the city or location for this trip.</small>
                    </label>

                    <label class="trip-form-field">
                        <span>Start Date</span>
                        <input type="date" name="start_date" value="<?= e($formTrip['start_date']) ?>" data-trip-start>
                    </label>

                    <label class="trip-form-field">
                        <span>End Date</span>
                        <input type="date" name="end_date" value="<?= e($formTrip['end_date']) ?>" data-trip-end>
                    </label>

                    <div class="trip-form-field trip-form-field--wide">
                        <span>Travel Type *</span>
                        <div class="trip-type-grid" data-trip-type-grid>
                            <label class="trip-type-option<?= $formTrip['travel_type'] === 'domestic' ? ' is-selected' : '' ?>" data-trip-type-option="domestic">
                                <input type="radio" name="travel_type" value="domestic"<?= $formTrip['travel_type'] === 'domestic' ? ' checked' : '' ?> data-trip-type-input>
                                <span class="trip-type-dot"></span>
                                <strong>Domestic</strong>
                                <small>You are creating this request for a trip within your home country.</small>
                            </label>
                            <label class="trip-type-option<?= $formTrip['travel_type'] === 'international' ? ' is-selected' : '' ?>" data-trip-type-option="international">
                                <input type="radio" name="travel_type" value="international"<?= $formTrip['travel_type'] === 'international' ? ' checked' : '' ?> data-trip-type-input>
                                <span class="trip-type-dot"></span>
                                <strong>International</strong>
                                <small>You are creating this request for a trip outside your home country.</small>
                            </label>
                        </div>
                    </div>

                    <label class="trip-form-field trip-form-field--wide">
                        <span>Business Purpose</span>
                        <textarea name="business_purpose" rows="4" placeholder="Max 250 characters" data-trip-purpose><?= e($formTrip['business_purpose']) ?></textarea>
                    </label>

                    <label class="trip-cover-dropzone trip-form-field--wide">
                        <input type="file" name="trip_cover" accept="image/*" data-trip-cover-input>
                        <span class="trip-cover-dropzone-icon">
                            <i class="fa-regular fa-image" aria-hidden="true"></i>
                        </span>
                        <strong>Upload a trip image</strong>
                        <small>Preview it instantly and save it with the trip.</small>
                    </label>
                </div>

                <footer class="trip-create-footer">
                    <button type="submit" class="trip-primary">Save and Continue</button>
                    <a class="trip-secondary" href="<?= e(page_url('trips')) ?>">Cancel</a>
                </footer>
            </form>
        </section>

        <aside class="trip-preview-panel panel">
            <div class="trip-preview-frame">
                <img class="<?= $previewCoverPath !== '' ? '' : 'is-hidden' ?>" src="<?= e($previewCoverPath !== '' ? trip_cover_url($previewCoverPath) : '') ?>" alt="" data-trip-cover-preview>
                <div class="trip-preview-placeholder<?= $previewCoverPath !== '' ? ' is-hidden' : '' ?>" data-trip-cover-placeholder>
                    <i class="fa-solid fa-suitcase" aria-hidden="true"></i>
                    <strong>Trip preview</strong>
                    <span>Upload an image to see it here.</span>
                </div>
            </div>

            <div class="trip-preview-summary">
                <div class="trip-preview-summary-top">
                    <span class="trip-preview-badge" data-trip-summary-type><?= e($previewTravelType) ?></span>
                    <strong data-trip-summary-name><?= e($previewTripName) ?></strong>
                    <p data-trip-summary-purpose><?= e($previewPurpose) ?></p>
                </div>

                <div class="trip-preview-meta">
                    <div class="trip-preview-row">
                        <span>Destination</span>
                        <strong data-trip-summary-destination><?= e($previewDestination) ?></strong>
                    </div>
                    <div class="trip-preview-row">
                        <span>Dates</span>
                        <strong data-trip-summary-dates><?= e($previewDateRange) ?></strong>
                    </div>
                    <div class="trip-preview-row">
                        <span>Status</span>
                        <strong data-trip-summary-status><?= e($previewStatus) ?></strong>
                    </div>
                </div>
            </div>
        </aside>
    </div>
</div>
<?php render_expense_shell_end(); ?>
