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

/*--------------------------------------------------------------
# Add / Edit Category - SaaS Modern UI (Aligned Styles)
--------------------------------------------------------------*/
function afdp_category_add_edit(){
   // Handle form submit logic
if ( isset( $_POST['afdp_cat_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['afdp_cat_nonce'] ) ), 'afdp_cat_action' ) ) {
    
    // Validate, Unslash, and Sanitize inputs
    $name   = isset( $_POST['afdp_cat_name'] ) ? sanitize_text_field( wp_unslash( $_POST['afdp_cat_name'] ) ) : '';
    $img_id = isset( $_POST['afdp_category_image'] ) ? intval( $_POST['afdp_category_image'] ) : 0;
    $order  = isset( $_POST['afdp_cat_order'] ) ? intval( $_POST['afdp_cat_order'] ) : 0; 
    $edit   = isset( $_POST['afdp_cat_edit'] ) ? intval( $_POST['afdp_cat_edit'] ) : 0;

    if ( $edit ) { 
        wp_update_term( $edit, 'afdp_food_category', [ 'name' => $name ] );
        update_term_meta( $edit, 'afdp_category_image', $img_id );
        update_term_meta( $edit, 'afdp_category_order', $order ); 
        echo '<div class="notice notice-success is-dismissible" style="border-left-color: #e53935;"><p>' . esc_html__( 'Category updated successfully.', 'food-delivery-pickup-soluition' ) . '</p></div>';
    } else { 
        $term = wp_insert_term( $name, 'afdp_food_category' );
        if ( ! is_wp_error( $term ) ) {
            if ( $img_id ) {
                add_term_meta( $term['term_id'], 'afdp_category_image', $img_id );
            }
            add_term_meta( $term['term_id'], 'afdp_category_order', $order );
            echo '<div class="notice notice-success is-dismissible" style="border-left-color: #e53935;"><p>' . esc_html__( 'Category created successfully.', 'food-delivery-pickup-soluition' ) . '</p></div>';
        } else {
            echo '<div class="error notice"><p>' . esc_html( $term->get_error_message() ) . '</p></div>';
        }
    }
}

    $edit_id      = isset($_GET['edit']) ? intval($_GET['edit']) : 0;
    $edit_term    = $edit_id ? get_term($edit_id, 'afdp_food_category') : null;
    $edit_img_id  = $edit_id ? get_term_meta($edit_id, 'afdp_category_image', true) : '';
    $edit_img_url = $edit_img_id ? wp_get_attachment_url($edit_img_id) : '';
    $edit_order   = $edit_id ? get_term_meta($edit_id, 'afdp_category_order', true) : 0; 
    ?>

    <style>
        :root { 
            --fd-primary: #e53935; 
            --fd-primary-hover: #c62828;
            --fd-border: #ccd0d4; 
            --fd-text: #1d2327;
        }

        .fd-cat-container { max-width: 550px; margin: 40px auto; }
        .fd-card { background: #fff; border-radius: 12px; border: 1px solid var(--fd-border); box-shadow: 0 4px 15px rgba(0,0,0,0.05); overflow: hidden; }
        .fd-card-header { padding: 25px; border-bottom: 1px solid #f0f0f1; background: #fff; text-align: center; }
        .fd-card-header h2 { margin: 0; font-size: 20px; font-weight: 700; color: var(--fd-text); }
        
        .fd-card-body { padding: 30px; }
        .fd-input-group { margin-bottom: 25px; }
        .fd-input-group label { display: block; font-weight: 600; margin-bottom: 8px; color: var(--fd-text); font-size: 14px; }
        
        .fd-styled-input { width: 100%; padding: 12px 15px; border: 1px solid var(--fd-border); border-radius: 8px; font-size: 15px; transition: 0.2s; box-sizing: border-box; }
        .fd-styled-input:focus { border-color: var(--fd-primary); outline: none; box-shadow: 0 0 0 3px rgba(229, 57, 53, 0.1); }
        
        /* Image Upload Zone */
        .fd-cat-upload-zone { border: 2px dashed var(--fd-border); border-radius: 12px; padding: 25px; text-align: center; cursor: pointer; transition: 0.3s; background: #fcfcfc; }
        .fd-cat-upload-zone:hover { border-color: var(--fd-primary); background: #fff5f5; }
        .fd-cat-upload-zone img { max-width: 100px; border-radius: 8px; box-shadow: 0 4px 10px rgba(0,0,0,0.1); margin-bottom: 10px; }
        
        /* Bootstrap Aligned Footer Buttons */
        .fd-card-footer { padding: 20px 30px; background: #f8f9fa; border-top: 1px solid #f0f0f1; display: flex; justify-content: space-between; align-items: center; }
        
        .btn-fd { 
            display: inline-flex; align-items: center; gap: 8px; padding: 10px 20px; 
            border-radius: 6px; font-size: 14px; font-weight: 600; text-decoration: none; 
            transition: all 0.2s ease; cursor: pointer; border: 1px solid transparent;
        }

        /* Cancel: Outline Style */
        .btn-outline-fd { color: #64748b; border-color: #cbd5e1; background: #fff; }
        .btn-outline-fd:hover { background: #f1f5f9; color: #1d2327; border-color: #94a3b8; }

        /* Save: Primary Style (Red) */
        .btn-primary-fd { color: #fff; background: var(--fd-primary); border-color: var(--fd-primary); }
        .btn-primary-fd:hover { background: var(--fd-primary-hover); border-color: var(--fd-primary-hover); box-shadow: 0 4px 12px rgba(229, 57, 53, 0.2); }
    </style>

    <div class="fd-cat-container">
        <div class="fd-card">
            <div class="fd-card-header">
                <h2><?php echo $edit_id ? 'Update Category' : 'Create New Category'; ?></h2>
            </div>
            
            <form method="post">
                <?php wp_nonce_field('afdp_cat_action','afdp_cat_nonce'); ?>
                <input type="hidden" name="afdp_cat_edit" value="<?php echo esc_attr($edit_id); ?>">
                
                <div class="fd-card-body">
                    <div class="fd-input-group">
                        <label>Category Name</label>
                        <input type="text" name="afdp_cat_name" class="fd-styled-input" 
                               placeholder="e.g. Italian Pizzas" 
                               value="<?php echo esc_attr($edit_term->name ?? ''); ?>" required>
                    </div>

                    <div class="fd-input-group">
                        <label>Display Order</label>
                        <input type="number" name="afdp_cat_order" class="fd-styled-input" 
                               placeholder="0" 
                               value="<?php echo esc_attr($edit_order); ?>">
                        <small style="color: #94a3b8; display:block; margin-top:5px;">Lower numbers (0, 1, 2) appear first in menus.</small>
                    </div>

                    <div class="fd-input-group">
                        <label>Category Image</label>
                        <input type="hidden" name="afdp_category_image" id="afdp_category_image" value="<?php echo esc_attr($edit_img_id); ?>">
                        
                        <div id="afdp_cat_dropzone" class="fd-cat-upload-zone">
                            <div id="afdp_cat_preview_inner">
                                <?php if($edit_img_url): ?>
                                    <img src="<?php echo esc_url($edit_img_url); ?>">
                                    <p style="margin:0; font-size:12px; color:var(--fd-primary); font-weight:600;">Change Image</p>
                                <?php else: ?>
                                    <span class="dashicons dashicons-camera" style="font-size: 30px; width: 30px; height: 30px; color: #cbd5e1;"></span>
                                    <p style="margin: 8px 0 0; color: #64748b; font-size:13px;">Click to upload image</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="fd-card-footer">
                    <a href="<?php echo esc_url(admin_url('admin.php?page=awesome_food_delivery&tab=categories')); ?>" class="btn-fd btn-outline-fd">
                        Cancel
                    </a>
                    <button type="submit" class="btn-fd btn-primary-fd">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"></path><polyline points="17 21 17 13 7 13 7 21"></polyline><polyline points="7 3 7 8 15 8"></polyline></svg>
                        <?php echo $edit_id ? 'Save Changes' : 'Create Category'; ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
    jQuery(function($){
        var frame;
        $('#afdp_cat_dropzone').on('click', function(e){
            e.preventDefault();
            if(frame){ frame.open(); return; }
            frame = wp.media({
                title: 'Select Category Image',
                button: { text: 'Use this image' },
                multiple: false
            });
            frame.on('select', function(){
                var attachment = frame.state().get('selection').first().toJSON();
                $('#afdp_category_image').val(attachment.id);
                $('#afdp_cat_preview_inner').html('<img src="'+attachment.url+'"><p style="margin:0; font-size:12px; color:var(--fd-primary); font-weight:600;">Change Image</p>');
            });
            frame.open();
        });
    });
    </script>
    <?php
}