<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/marketing.php';

$user = sparrow_require_backyard_login();

$post_id = (int) ($_GET['id'] ?? 0);
$post = $post_id > 0 ? sparrow_get_marketing_post($post_id) : null;

if ($post_id > 0 && !$post) {
    sparrow_backyard_header('Marketing Post Not Found');
    ?>

    <section class="card">
        <h1>Marketing Post Not Found</h1>
        <p class="muted">That marketing post could not be found.</p>

        <a class="button" href="<?php echo sparrow_escape(sparrow_url('/backyard/marketing.php')); ?>">
            Back to Marketing
        </a>
    </section>

    <?php
    sparrow_backyard_footer();
    exit;
}

$notice = '';
$error = '';

function sparrow_store_marketing_uploaded_file(string $tmp_name, string $original_name): ?string
{
    if ($tmp_name === '' || $original_name === '') {
        return null;
    }

    if (!is_uploaded_file($tmp_name)) {
        return null;
    }

    $upload_dir = dirname(__DIR__) . '/storage/marketing/';

    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed, true)) {
        return null;
    }

    $file_name = 'marketing-' . time() . '-' . bin2hex(random_bytes(4)) . '.' . $ext;
    $destination = $upload_dir . $file_name;

    if (!move_uploaded_file($tmp_name, $destination)) {
        return null;
    }

    return '/storage/marketing/' . $file_name;
}

function sparrow_marketing_datetime_for_input(?string $value): string
{
    if (empty($value)) {
        return '';
    }

    $timestamp = strtotime($value);

    if (!$timestamp) {
        return '';
    }

    return date('Y-m-d\TH:i', $timestamp);
}

function sparrow_marketing_datetime_for_db(string $value): string
{
    $value = trim($value);

    if ($value === '') {
        return '';
    }

    $timestamp = strtotime($value);

    if (!$timestamp) {
        return '';
    }

    return date('Y-m-d H:i:s', $timestamp);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save_marketing_post') {
        try {
            $image_path = $_POST['existing_image_path'] ?? '';

            if (!empty($_FILES['image_upload']['name'])) {
                $tmp_name = $_FILES['image_upload']['tmp_name'] ?? '';
                $original_name = $_FILES['image_upload']['name'] ?? '';
                $error_code = $_FILES['image_upload']['error'] ?? UPLOAD_ERR_NO_FILE;

                if ($error_code === UPLOAD_ERR_OK) {
                    $uploaded_path = sparrow_store_marketing_uploaded_file($tmp_name, $original_name);

                    if ($uploaded_path) {
                        $image_path = $uploaded_path;
                    }
                }
            }

            $saved_id = sparrow_save_marketing_post([
                'title' => $_POST['title'] ?? '',
                'image_path' => $image_path,
                'message' => $_POST['message'] ?? '',
                'short_prayer' => $_POST['short_prayer'] ?? '',
                'promotion' => $_POST['promotion'] ?? '',
                'hashtags' => $_POST['hashtags'] ?? '',
                'platform_facebook' => $_POST['platform_facebook'] ?? '',
                'platform_instagram' => $_POST['platform_instagram'] ?? '',
                'show_public_blog' => $_POST['show_public_blog'] ?? '',
                'status' => $_POST['status'] ?? 'Draft',
                'scheduled_at' => sparrow_marketing_datetime_for_db($_POST['scheduled_at'] ?? ''),
                'posted_at' => sparrow_marketing_datetime_for_db($_POST['posted_at'] ?? ''),
            ], $post_id);

            sparrow_redirect('/backyard/marketing-edit.php?id=' . $saved_id . '&saved=1');
        } catch (Throwable $e) {
            $error = $e->getMessage();
        }
    }
}

if (!empty($_GET['saved'])) {
    $notice = 'Marketing post saved.';
}

if (!empty($_GET['from_gallery'])) {
    $notice = 'Marketing post created from gallery item.';
}

$post = $post_id > 0 ? sparrow_get_marketing_post($post_id) : [
    'title' => '',
    'image_path' => '',
    'message' => '',
    'short_prayer' => '',
    'promotion' => '',
    'hashtags' => '',
    'platform_facebook' => 1,
    'platform_instagram' => 1,
    'show_public_blog' => 0,
    'status' => 'Draft',
    'scheduled_at' => '',
    'posted_at' => '',
];

$caption = sparrow_compose_marketing_caption($post);
$statuses = sparrow_marketing_statuses();

sparrow_backyard_header($post_id > 0 ? 'Edit Marketing Post' : 'Add Marketing Post');

?>

<?php if ($notice): ?>
    <div class="notice-success">
        <?php echo sparrow_escape($notice); ?>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="notice-error">
        <?php echo sparrow_escape($error); ?>
    </div>
<?php endif; ?>

<section class="card">
    <div class="page-heading-row">
        <div>
            <h1><?php echo $post_id > 0 ? 'Edit Marketing Post' : 'Add Marketing Post'; ?></h1>
            <p class="muted">
                Build a caption draft for Facebook, Instagram, and public product stories.
            </p>
        </div>

        <div class="heading-actions">
            <a class="button" href="<?php echo sparrow_escape(sparrow_url('/backyard/marketing-edit.php')); ?>">
                Add Another Post
            </a>

            <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/marketing.php')); ?>">
                Back to Marketing
            </a>

            <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/blog.php')); ?>" target="_blank">
                View Blog
            </a>
        </div>
    </div>
</section>

<section class="card">
    <h2>Post Details</h2>

    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="action" value="save_marketing_post">
        <input type="hidden" name="existing_image_path" value="<?php echo sparrow_escape($post['image_path'] ?? ''); ?>">

        <div class="form-grid">
            <div>
                <label for="title">Title</label>
                <input
                    type="text"
                    id="title"
                    name="title"
                    value="<?php echo sparrow_escape($post['title'] ?? ''); ?>"
                    required
                >
            </div>

            <div>
                <label for="status">Status</label>
                <select id="status" name="status">
                    <?php foreach ($statuses as $status): ?>
                        <option
                            value="<?php echo sparrow_escape($status); ?>"
                            <?php echo (($post['status'] ?? 'Draft') === $status) ? 'selected' : ''; ?>
                        >
                            <?php echo sparrow_escape($status); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label for="scheduled_at">Scheduled Date/Time</label>
                <input
                    type="datetime-local"
                    id="scheduled_at"
                    name="scheduled_at"
                    value="<?php echo sparrow_escape(sparrow_marketing_datetime_for_input($post['scheduled_at'] ?? '')); ?>"
                >
            </div>

            <div>
                <label for="posted_at">Posted Date/Time</label>
                <input
                    type="datetime-local"
                    id="posted_at"
                    name="posted_at"
                    value="<?php echo sparrow_escape(sparrow_marketing_datetime_for_input($post['posted_at'] ?? '')); ?>"
                >
            </div>
        </div>

        <div class="form-grid">
            <div>
                <label>
                    <input
                        type="checkbox"
                        name="platform_facebook"
                        value="1"
                        style="width:auto;"
                        <?php echo !empty($post['platform_facebook']) ? 'checked' : ''; ?>
                    >
                    Facebook
                </label>
            </div>

            <div>
                <label>
                    <input
                        type="checkbox"
                        name="platform_instagram"
                        value="1"
                        style="width:auto;"
                        <?php echo !empty($post['platform_instagram']) ? 'checked' : ''; ?>
                    >
                    Instagram
                </label>
            </div>

            <div>
                <label>
                    <input
                        type="checkbox"
                        name="show_public_blog"
                        value="1"
                        style="width:auto;"
                        <?php echo !empty($post['show_public_blog']) ? 'checked' : ''; ?>
                    >
                    Show on Public Blog
                </label>
            </div>
        </div>

        <div class="form-section">
            <label for="image_upload">Product Image</label>

            <?php if (!empty($post['image_path'])): ?>
                <div class="marketing-image-preview">
                    <img
                        src="<?php echo sparrow_escape(sparrow_url($post['image_path'])); ?>"
                        alt="<?php echo sparrow_escape($post['title'] ?? 'Marketing image'); ?>"
                    >
                </div>
            <?php endif; ?>

            <input
                type="file"
                id="image_upload"
                name="image_upload"
                accept="image/jpeg,image/png,image/gif,image/webp"
            >

            <p class="muted">
                Upload a new image only if you want to add or replace the current one.
            </p>
        </div>

        <div class="form-section">
            <label for="message">Message / Story</label>
            <textarea id="message" name="message" rows="5"><?php echo sparrow_escape($post['message'] ?? ''); ?></textarea>
        </div>

        <div class="form-section">
            <label for="short_prayer">Short Prayer</label>
            <textarea id="short_prayer" name="short_prayer" rows="3"><?php echo sparrow_escape($post['short_prayer'] ?? ''); ?></textarea>
        </div>

        <div class="form-section">
            <label for="promotion">Promotion</label>
            <textarea id="promotion" name="promotion" rows="3"><?php echo sparrow_escape($post['promotion'] ?? ''); ?></textarea>
        </div>

        <div class="form-section">
            <label for="hashtags">Hashtags</label>
            <textarea id="hashtags" name="hashtags" rows="3" placeholder="#customshirts #faithbasedbusiness #sparrowandseed"><?php echo sparrow_escape($post['hashtags'] ?? ''); ?></textarea>
        </div>

        <div class="form-actions">
            <button type="submit" class="button">
                Save Marketing Post
            </button>

            <a class="button button-secondary" href="<?php echo sparrow_escape(sparrow_url('/backyard/marketing.php')); ?>">
                Cancel
            </a>
        </div>
    </form>
</section>

<section class="card">
    <h2>Caption Preview</h2>

    <textarea
        id="captionPreview"
        class="marketing-caption-preview"
        rows="12"
        readonly
    ><?php echo sparrow_escape($caption); ?></textarea>

    <div class="form-actions">
        <button type="button" class="button" id="copyCaptionButton">
            Copy Caption
        </button>

        <a class="button button-secondary" href="https://business.facebook.com/" target="_blank">
            Open Facebook
        </a>

        <a class="button button-secondary" href="https://www.instagram.com/" target="_blank">
            Open Instagram
        </a>
    </div>

    <p class="muted" id="copyCaptionNotice" style="display:none;">
        Caption copied.
    </p>
</section>

<script>
    const copyCaptionButton = document.getElementById('copyCaptionButton');
    const captionPreview = document.getElementById('captionPreview');
    const copyCaptionNotice = document.getElementById('copyCaptionNotice');

    if (copyCaptionButton && captionPreview) {
        copyCaptionButton.addEventListener('click', async () => {
            try {
                await navigator.clipboard.writeText(captionPreview.value);

                if (copyCaptionNotice) {
                    copyCaptionNotice.style.display = 'block';

                    setTimeout(() => {
                        copyCaptionNotice.style.display = 'none';
                    }, 2200);
                }
            } catch (error) {
                captionPreview.select();
                document.execCommand('copy');

                if (copyCaptionNotice) {
                    copyCaptionNotice.style.display = 'block';

                    setTimeout(() => {
                        copyCaptionNotice.style.display = 'none';
                    }, 2200);
                }
            }
        });
    }
</script>

<?php sparrow_backyard_footer(); ?>