<?php
if (!defined('ABSPATH')) exit;

/* =========================
   LOAD EDIT DATA (IF ANY)
========================= */
// $edit_id = intval($_GET['edit'] ?? 0);
// $edit_id = isset($_GET['edit']) && !isset($_GET['add'])
//     ? intval($_GET['edit'])
//     : 0;

$is_add  = isset($_GET['add']);
$is_edit = isset($_GET['edit']) && !$is_add;

$show_form = ($is_add || $is_edit);

$edit_id = $is_edit ? intval($_GET['edit']) : 0;
$product = $edit_id ? get_post($edit_id) : null;

if ($is_add) {
    $product = null;
}

$meta = function ($key) use ($edit_id) {
    return $edit_id ? get_post_meta($edit_id, $key, true) : '';
};

$categories = get_terms([
    'taxonomy'   => 'product_category',
    'hide_empty' => false
]);

?>

<style>
    div#wpbody-content {
        padding: 0.5rem 1rem;
    }
    :root {
        --primary-color: #0073aa;
        --primary-hover: #005a87;
        --danger-color: #d63638;
        --success-color: #00a032;
        --border-color: #dcdcde;
        --bg-light: #f6f7f7;
        --bg-white: #FAFAFA;
        --text-dark: #1e1e1e;
        --text-muted: #646970;
        --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
        --shadow-md: 0 2px 8px rgba(0, 0, 0, 0.1);
        --radius-sm: 4px;
        --radius-md: 8px;
        --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }


    * {
        box-sizing: border-box;
    }

    iframe {
        height: 250px !important;
    }

    .ipm-form-title {
        margin: 10px 0 32px;
        font-size: 1.2rem;
        font-weight: 600;
        color: var(--text-dark);
        letter-spacing: -0.5px;
        width: fit-content;
        padding: 10px 20px;
        background: var(--bg-white);
        border: 1px solid var(--border-color);
    }

    .ipm-admin-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 24px;
        max-width: 1600px;
    }

    .ipm-col-main {
        flex: 1 1 60%;
        min-width: 0;
    }

    .ipm-col-sidebar {
        flex: 0 1 35%;
        min-width: 320px;
        display: flex;
        flex-direction: column;
        gap: 24px;
    }


    .ipm-card {
        background: var(--bg-white);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        padding: 24px;
        box-shadow: var(--shadow-sm);
        transition: var(--transition);
    }

    .ipm-card:hover {
        box-shadow: var(--shadow-md);
        border-color: var(--primary-color);
    }

    .ipm-card-title {
        font-size: 14px;
        font-weight: 700;
        color: var(--text-muted);
        text-transform: uppercase;
        letter-spacing: 0.5px;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 2px solid var(--bg-light);
    }


    .ipm-field {
        margin-bottom: 20px;
    }

    .ipm-field:last-child {
        margin-bottom: 0;
    }

    .ipm-field label {
        display: block;
        font-size: 14px;
        font-weight: 600;
        color: var(--text-dark);
        margin-bottom: 8px;
        letter-spacing: -0.2px;
    }

    .ipm-field input[type="text"],
    .ipm-field input[type="url"],
    .ipm-field input[type="email"],
    .ipm-field input[type="number"],
    .ipm-field select,
    .ipm-field textarea {
        width: 100%;
        padding: 10px 12px;
        font-size: 14px;
        border: 1px solid var(--border-color);
        border-radius: var(--radius-sm);
        background: var(--bg-white);
        color: var(--text-dark);
        transition: var(--transition);
        font-family: inherit;
    }

    .ipm-field input[type="text"]:focus,
    .ipm-field input[type="url"]:focus,
    .ipm-field input[type="email"]:focus,
    .ipm-field input[type="number"]:focus,
    .ipm-field select:focus,
    .ipm-field textarea:focus {
        outline: none;
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(0, 115, 170, 0.1);
        background: var(--bg-white);
    }

    .ipm-field textarea {
        resize: vertical;
        min-height: 100px;
        line-height: 1.5;
    }

    .wp-editor-wrap {
        margin-top: 8px;
        border: 1px solid var(--border-color);
        border-radius: var(--radius-sm);
        overflow: hidden;
    }

    .wp-editor-container {
        background: var(--bg-white);
    }

    .ipm-required::after {
        content: '*';
        color: var(--danger-color);
        margin-left: 4px;
        font-weight: 700;
    }


    .button {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 8px 16px;
        font-size: 14px;
        font-weight: 600;
        border: 1px solid var(--border-color);
        border-radius: var(--radius-sm);
        background: var(--bg-white);
        color: var(--text-dark);
        cursor: pointer;
        transition: var(--transition);
        text-decoration: none;
    }

    .button:hover {
        background: var(--bg-light);
        border-color: var(--primary-color);
        color: var(--primary-color);
    }

    .button-primary {
        background: var(--primary-color);
        color: white;
        border-color: var(--primary-color);
    }

    .button-primary:hover {
        background: var(--primary-hover);
        border-color: var(--primary-hover);
    }

    .button-large {
        padding: 12px 24px;
        font-size: 16px;
        width: 100%;
    }

    .ipm-upload {
        width: 100%;
    }


    .ipm-preview {
        margin-top: 12px;
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
    }

    .ipm-preview img {
        max-width: 120px;
        height: 120px;
        object-fit: cover;
        border-radius: var(--radius-md);
        border: 1px solid var(--border-color);
        box-shadow: var(--shadow-sm);
    }

    .ipm-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 16px;
    }

    .ipm-row.full {
        grid-template-columns: 1fr;
    }

    .ipm-row-item {
        min-width: 0;
    }


    .ipm-col-sidebar .ipm-card {
        background: var(--bg-light);
        border-color: var(--border-color);
    }

    .ipm-col-sidebar .ipm-card:hover {
        background: var(--bg-white);
        border-color: var(--primary-color);
    }

    .ipm-submit {
        margin-top: 32px;
        display: flex;
        gap: 12px;
        justify-content: flex-end;
    }

    .ipm-submit-right {
        margin-top: 0;
        text-align: right;
        display: flex;
        gap: 8px;
        justify-content: flex-end;
    }

    .widefat td, .widefat th {
        vertical-align: middle !important;
    }
    @media (max-width: 1200px) {
        .ipm-admin-grid {
            flex-direction: column;
        }

        .ipm-col-main,
        .ipm-col-sidebar {
            flex: 1 1 100%;
        }

        .ipm-col-sidebar {
            flex-direction: row;
            flex-wrap: wrap;
        }

        .ipm-card {
            flex: 1 1 calc(50% - 12px);
            min-width: 280px;
        }
       
    }

    @media (max-width: 768px) {
        .ipm-form-title {
            font-size: 24px;
            margin-bottom: 24px;
        }

        .ipm-admin-grid {
            gap: 16px;
        }

        .ipm-col-sidebar {
            flex-direction: column;
        }

        .ipm-card {
            flex: 1 1 100%;
        }

        .ipm-row {
            grid-template-columns: 1fr;
        }

        .button-large {
            padding: 10px 16px;
            font-size: 14px;
        }
    }

    .ipm-field input:disabled,
    .ipm-field select:disabled,
    .ipm-field textarea:disabled {
        background: var(--bg-light);
        color: var(--text-muted);
        cursor: not-allowed;
    }

    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .ipm-card {
        animation: slideIn 0.3s ease-out;
    }

    .ipm-hidden {
        display: none;
    }

    #ipm-product-form,
    .ipm-submit-right {
        margin: 10px auto;
    }
</style>

<!-- <h2 class="ipm-form-title">
    <?php echo $edit_id ? '✏️ Edit Product' : '➕ Add New Product'; ?>
</h2> -->


<form method="post"
    id="ipm-product-form"
    class="<?php echo $show_form ? '' : 'ipm-hidden'; ?>">
    <div class="ipm-submit-right">
        <button type="button"
            id="ipm-close-form"
            class="button">
            ✖ Close Form
        </button>
    </div>

    <?php wp_nonce_field('ipm_save_product', '_ipm_product_nonce'); ?>
    <!-- <input type="hidden" name="product_id" value="<?php echo esc_attr($edit_id); ?>"> -->
    <input type="hidden" name="product_id" value="<?php echo esc_attr($edit_id ?: ''); ?>">

    <div class="ipm-admin-grid">

        <!-- ================= MAIN COLUMN ================= -->
        <div class="ipm-col-main">

            <!-- BASIC INFO CARD -->
            <div class="ipm-card">
                <div class="ipm-field">
                    <div class="ipm-row">
                        <div class="ipm-row-item">
                            <div class="ipm-field">
                                <label class="ipm-required">Product Name</label>
                                <input type="text"
                                    name="product_title"
                                    required
                                    placeholder="Enter product name..."
                                    value="<?php echo esc_attr($product->post_title ?? ''); ?>">
                            </div>
                        </div>
                        <div class="ipm-row-item">
                            <div class="ipm-field">
                                <label>Product Category</label>
                                <select name="product_category">
                                    <option value="">— Select Category —</option>
                                    <?php foreach ($categories as $cat): ?>
                                        <option value="<?php echo esc_attr($cat->term_id); ?>"
                                            <?php
                                            if ($edit_id) {
                                                $terms = wp_get_post_terms($edit_id, 'product_category', ['fields' => 'ids']);
                                                selected(in_array($cat->term_id, $terms));
                                            }
                                            ?>>
                                            <?php echo esc_html($cat->name); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="ipm-field">
                    <label>Product Description</label>
                    <?php wp_editor(
                        $product->post_content ?? '',
                        'product_description',
                        [
                            'textarea_name' => 'product_description',
                            'media_buttons' => true,
                            'teeny' => false,
                            'quicktags' => true,
                        ]
                    ); ?>
                </div>

                <div class="ipm-field">
                    <label>Product Features</label>
                    <?php wp_editor(
                        $meta('product_features'),
                        'product_features',
                        ['textarea_name' => 'product_features']
                    ); ?>
                </div>



                <div class="ipm-field">
                    <label>Warranty Details</label>
                    <?php wp_editor(
                        $meta('warranty_details'),
                        'warranty_details',
                        ['textarea_name' => 'warranty_details']
                    ); ?>
                </div>

                <div class="ipm-field">
                    <label>Accessories</label>
                    <?php wp_editor(
                        $meta('accessories'),
                        'accessories',
                        ['textarea_name' => 'accessories']
                    ); ?>
                </div>
            </div>

        </div>

        <!-- ================= SIDEBAR COLUMN ================= -->
        <div class="ipm-col-sidebar">

            <!-- STATUS CARD -->
            <div class="ipm-card">
                <div class="ipm-card-title">Publish</div>

                <div class="ipm-field">
                    <label>Product Status</label>
                    <select name="product_status">
                        <option value="publish" <?php selected($product->post_status ?? '', 'publish'); ?>>📌 Active</option>
                        <option value="draft" <?php selected($product->post_status ?? '', 'draft'); ?>>📝 Draft</option>
                    </select>
                </div>

                <div class="ipm-submit-right">
                    <button type="submit" name="ipm_save_product" class="button button-primary button-large">
                        <!-- <?php echo $edit_id ? 'Update Product' : 'Save Product'; ?> -->
                        <?php echo $is_edit ? 'Update Product' : 'Save Product'; ?>
                    </button>
                </div>
            </div>

            <!-- MEDIA CARD -->
            <div class="ipm-card">
                <div class="ipm-card-title">Featured Image</div>

                <div class="ipm-field">
                    <input type="hidden" name="featured_image_id" id="featured_image_id"
                        value="<?php echo esc_attr(get_post_thumbnail_id($edit_id)); ?>">
                    <button type="button" class="button ipm-upload" data-target="featured_image_id">
                        🖼️ Upload Featured Image
                    </button>
                    <div class="ipm-preview">
                        <?php echo $edit_id ? get_the_post_thumbnail($edit_id, [120, 120]) : ''; ?>
                    </div>
                </div>
            </div>

            <!-- GALLERY CARD -->
            <div class="ipm-card">
                <div class="ipm-card-title">Gallery Images</div>

                <?php for ($i = 1; $i <= 3; $i++): ?>
                    <div class="ipm-field">
                        <input type="hidden"
                            name="gallery_image_<?php echo $i; ?>"
                            id="gallery_image_<?php echo $i; ?>"
                            value="<?php echo esc_attr($meta('gallery_image_' . $i)); ?>">
                        <button type="button"
                            class="button ipm-upload"
                            data-target="gallery_image_<?php echo $i; ?>">
                            📸 Gallery Image <?php echo $i; ?>
                        </button>
                    </div>
                <?php endfor; ?>
            </div>

            <!-- SPECIFICATIONS CARD -->
            <div class="ipm-card">
                <div class="ipm-card-title">Specifications</div>

                <div class="ipm-field">
                    <label>Product Dimensions</label>
                    <input type="text"
                        name="product_dimension"
                        placeholder="e.g., 10 x 20 x 30 cm"
                        value="<?php echo esc_attr($meta('product_dimension')); ?>">
                </div>

                <div class="ipm-field">
                    <label>PDF Catalog Link</label>
                    <input type="url"
                        name="product_pdf"
                        placeholder="https://example.com/catalog.pdf"
                        value="<?php echo esc_url($meta('product_pdf')); ?>">
                </div>

                <div class="ipm-field">
                    <label>YouTube Embed Link</label>
                    <input type="url"
                        name="youtube_url"
                        placeholder="https://www.youtube.com/watch?v=xxxx"
                        value="<?php echo esc_url($meta('youtube_url')); ?>">
                </div>
            </div>

            <!-- SEO CARD -->
            <div class="ipm-card">
                <div class="ipm-card-title">SEO Settings</div>

                <div class="ipm-field">
                    <label>Meta Slug</label>
                    <input type="text"
                        name="meta_slug"
                        placeholder="product-slug"
                        value="<?php echo esc_attr($meta('meta_slug')); ?>">
                </div>

                <div class="ipm-field">
                    <label>Meta Title</label>
                    <input type="text"
                        name="meta_title"
                        placeholder="Page title (50-60 chars)"
                        value="<?php echo esc_attr($meta('meta_title')); ?>">
                </div>

                <div class="ipm-field">
                    <label>Meta Description</label>
                    <textarea name="meta_description"
                        placeholder="Page description (150-160 chars)"><?php echo esc_textarea($meta('meta_description')); ?></textarea>
                </div>

                <div class="ipm-field">
                    <label>Meta Keywords</label>
                    <input type="text"
                        name="meta_keywords"
                        placeholder="keyword1, keyword2, keyword3"
                        value="<?php echo esc_attr($meta('meta_keywords')); ?>">
                </div>
            </div>

        </div>

    </div>

    <!-- BOTTOM SUBMIT -->
    <div class="ipm-submit">
        <button type="submit" name="ipm_save_product" class="button button-primary button-large">
            <!-- <?php echo $edit_id ? '✓ Update Product' : '✓ Save Product'; ?> -->
            <?php echo $is_edit ? 'Update Product' : 'Save Product'; ?>
        </button>
    </div>

</form>

<script>
    jQuery(document).ready(function($) {

        let mediaFrame = null;
        let activeTarget = null;

        $('.ipm-upload').on('click', function(e) {
            e.preventDefault();

            activeTarget = $(this).data('target');

            if (mediaFrame) {
                mediaFrame.open();
                return;
            }

            mediaFrame = wp.media({
                title: 'Select Image',
                button: {
                    text: 'Use Image'
                },
                library: {
                    type: 'image'
                },
                multiple: false
            });

            mediaFrame.on('select', function() {
                const attachment = mediaFrame.state()
                    .get('selection')
                    .first()
                    .toJSON();

                // Set hidden field
                $('#' + activeTarget).val(attachment.id);

                const imgHTML = `
                <img src="${attachment.url}" alt="" />
            `;

                /* =============================
                   FEATURED IMAGE
                ============================= */
                if (activeTarget === 'featured_image_id') {
                    $('.ipm-card:has(#featured_image_id) .ipm-preview')
                        .html(imgHTML);
                    return;
                }

                /* =============================
                   GALLERY IMAGE (1–3)
                ============================= */
                const galleryIndex = activeTarget.replace('gallery_image_', '');

                let galleryCard = $('.ipm-card-title:contains("Gallery Images")')
                    .closest('.ipm-card');

                let previewWrap = galleryCard.find('.ipm-preview');

                if (!previewWrap.length) {
                    galleryCard.append('<div class="ipm-preview"></div>');
                    previewWrap = galleryCard.find('.ipm-preview');
                }

                let existing = previewWrap.find('[data-index="' + galleryIndex + '"]');

                if (existing.length) {
                    existing.find('img').attr('src', attachment.url);
                } else {
                    previewWrap.append(
                        `<div data-index="${galleryIndex}">
                        ${imgHTML}
                     </div>`
                    );
                }
            });

            mediaFrame.open();
        });

        const form = $('#ipm-product-form');

        /* =========================
           ADD NEW PRODUCT
        ========================= */
        $('#ipm-add-new').on('click', function() {
            window.location.href = 'admin.php?page=ipm-products&add=1';
        });
        // /* =========================
        //    AUTO SHOW ON EDIT
        // ========================= */
        // const params = new URLSearchParams(window.location.search);
        // if (params.has('edit')) {
        //     form.removeClass('ipm-hidden');

        //     $('html, body').animate({
        //         scrollTop: form.offset().top - 100
        //     }, 400);
        // }

        $('#ipm-close-form').on('click', function() {
            window.location.href = 'admin.php?page=ipm-products';
        });


    });
</script>