<?php
/**
 * Plugin Name: Awesome Food Ordering, Delivery & Pickup Solution
 * Description: Awesome Food Delivery & Pickup Solution is a professional-grade ERP solution.
 * Version: 1.0.1
 * Author: Abdullah Nahian
 * Author URI: https://devnahian.com
 * Text Domain: food-delivery-pickup-soluition
 * License: GPL2
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

if ( ! defined( 'ABSPATH' ) ) exit;

// Constants
define( 'AFDP_VERSION', '1.0.0' );
define( 'AFDP_PATH', plugin_dir_path( __FILE__ ) );
define( 'AFDP_URL', plugin_dir_url( __FILE__ ) );

/*--------------------------------------------------------------
# 1. Enqueue Scripts & Styles
--------------------------------------------------------------*/
function afdp_enqueue_scripts() {
    wp_enqueue_style( 'bootstrap', AFDP_URL . 'assets/css/bootstrap.min.css', array(), AFDP_VERSION );
    wp_enqueue_style( 'font-awesome', AFDP_URL . 'assets/css/font-awesome.min.css', array(), AFDP_VERSION );
    wp_enqueue_style( 'swiper', AFDP_URL . 'assets/css/swiper-bundle.min.css', array(), AFDP_VERSION );
    wp_enqueue_style( 'validnavs', AFDP_URL . 'assets/css/validnavs.css', array(), AFDP_VERSION );
    wp_enqueue_style( 'helper', AFDP_URL . 'assets/css/helper.css', array(), AFDP_VERSION );
    wp_enqueue_style( 'main-style', AFDP_URL . 'assets/css/style.css', array(), AFDP_VERSION );
    wp_enqueue_style( 'responsive-style', AFDP_URL . 'assets/css/responsive.css', array(), AFDP_VERSION );
    
    // Plugin custom style.css (if exists in root)
    if(file_exists(AFDP_PATH . 'style.css')){
        wp_enqueue_style( 'afdp-custom-style', AFDP_URL . 'style.css', array(), AFDP_VERSION );
    }

    wp_enqueue_script( 'jquery' );
    wp_enqueue_script( 'bootstrap', AFDP_URL . 'assets/js/bootstrap.bundle.min.js', array('jquery'), AFDP_VERSION, true );
    wp_enqueue_script( 'swiper', AFDP_URL . 'assets/js/swiper-bundle.min.js', array('jquery'), AFDP_VERSION, true );
    wp_enqueue_script( 'gsap', AFDP_URL . 'assets/js/gsap.js', array(), AFDP_VERSION, true );
    wp_enqueue_script( 'awesome-food-delivery-main', AFDP_URL . 'assets/js/main.js', array('jquery'), AFDP_VERSION, true );
}
add_action( 'wp_enqueue_scripts', 'afdp_enqueue_scripts' );

function afdp_admin_enqueue_scripts() {
    wp_enqueue_style( 'afdp-admin-style', AFDP_URL . 'assets/css/admin-style.css', array(), AFDP_VERSION );
    wp_enqueue_script( 'afdp-admin-script', AFDP_URL . 'assets/js/admin-script.js', array('jquery'), AFDP_VERSION, true );
}
add_action( 'admin_enqueue_scripts', 'afdp_admin_enqueue_scripts' );

/*--------------------------------------------------------------
# 2. Register Post Types and Taxonomy (Updated Namespacing)
--------------------------------------------------------------*/
add_action('init', function(){
    register_post_type('afdp_food_item', [
        'labels'=>['name'=>'Food Items','singular_name'=>'Food Item'],
        'public'=>false,'show_ui'=>false,'supports'=>['title','editor','thumbnail'],
    ]);

    register_post_type('afdp_food_order', [
        'labels'=>['name'=>'Orders','singular_name'=>'Order'],
        'public'=>false,'show_ui'=>false,'supports'=>['title','editor'],
    ]);

    register_post_type('afdp_food_customer', [
        'labels'=>['name'=>'Customers','singular_name'=>'Customer'],
        'public'=>false,'show_ui'=>false,'supports'=>['title','editor'],
    ]);

    register_taxonomy('afdp_food_category','afdp_food_item',[
        'labels'=>['name'=>'Food Categories','singular_name'=>'Food Category'],
        'hierarchical'=>true,
        'show_ui'=>false
    ]);
});

/*--------------------------------------------------------------
# 3. Admin Menu
--------------------------------------------------------------*/
add_action('admin_menu', function(){
    add_menu_page(
        'Food Delivery',
        'Food Delivery',
        'manage_options',
        'awesome_food_delivery',
        'afdp_main_page',
        'dashicons-carrot',
        20
    );
});

/*--------------------------------------------------------------
# 4. Main Admin Page UI
--------------------------------------------------------------*/
function afdp_main_page(){
    $tabs = [
        'dashboard'  => 'Dashboard',
        'orders'     => 'Orders',
        'items'      => 'Items',
        'categories' => 'Categories',
        'extras'     => 'Extras',
        'reports'    => 'Reports',
        'customers'  => 'Customers',
        'payments'   => 'Payments',   
        'shortcodes' => 'Shortcodes', 
        'settings'   => 'Settings'
    ];

    $active = $_GET['tab'] ?? 'dashboard';
    
    // Get the current label for the header
    $current_label = $tabs[$active] ?? 'Dashboard';
    ?>

    <div class="afdp-admin-wrapper" style="margin-top: 30px; padding-right: 20px;">
        
        <div class="afdp-main-header" style="margin-bottom: 25px; padding-left: 5px;">
            <div style="display: flex; align-items: center; gap: 15px;">
                <div style="background: #2271b1; width: 4px; height: 35px; border-radius: 2px;"></div>
                <div>
                    <h1 style="margin: 0; font-size: 24px; font-weight: 700; color: #1d2327;">
                        Awesome Food Delivery
                    </h1>
                    <p style="margin: 2px 0 0; color: #646970; font-size: 13px;">
                        Manage your restaurant / <?php echo esc_html($current_label); ?>
                    </p>
                </div>
            </div>
        </div>

        <div class="awesome-food-delivery">
            <?php if (!(isset($_GET['action']) && $_GET['action'] === 'print')) : ?>
                <ul class="afdp-left-tabs">
                    <?php 
                    $tab_icons = [
                        'dashboard'  => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>',
                        'orders'     => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z"></path><line x1="3" y1="6" x2="21" y2="6"></line><path d="M16 10a4 4 0 0 1-8 0"></path></svg>',
                        'items'      => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m7.5 4.27 9 5.15"></path><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"></path><path d="m3.3 7 8.7 5 8.7-5"></path><path d="M12 22V12"></path></svg>',
                        'categories' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg>',
                        'extras'     => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 3v19"></path><path d="M5 8h14"></path><path d="M15 21a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H9a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h6Z"></path></svg>',
                        'customers'  => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>',
                        'payments'   => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="5" width="20" height="14" rx="2"></rect><line x1="2" y1="10" x2="22" y2="10"></line></svg>',
                        'reports'    => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="20" x2="18" y2="10"></line><line x1="12" y1="20" x2="12" y2="4"></line><line x1="6" y1="20" x2="6" y2="14"></line></svg>',
                        'shortcodes' => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg>',
                        'settings'   => '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>',
                    ];
                    ?>

                    <?php foreach ($tabs as $key => $label) : ?>
                        <li>
                            <a class="<?php echo ($active === $key) ? 'active' : ''; ?>" 
                               href="<?php echo esc_url(admin_url('admin.php?page=awesome_food_delivery&tab=' . $key)); ?>">
                                <span class="afdp-tab-icon">
                                    <?php echo wp_kses_post( $tab_icons[$key] ?? '' ); ?>
                                </span>
                                <span class="afdp-tab-label"><?php echo esc_html($label); ?></span>
                            </a>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>

            <div class="afdp-right-box">
                <?php
                switch($active){
                    case 'dashboard':  if(function_exists('afdp_dashboard_tab')) afdp_dashboard_tab(); break;
                    case 'orders':     if(function_exists('afdp_orders_tab')) afdp_orders_tab(); break;
                    case 'items':      if(function_exists('afdp_items_tab')) afdp_items_tab(); break;
                    case 'categories': if(function_exists('afdp_category_tab')) afdp_category_tab(); break;
                    case 'extras':     if(function_exists('afdp_extras_tab')) afdp_extras_tab(); break;
                    case 'reports':    if(function_exists('afdp_reports_tab')) afdp_reports_tab(); break;
                    case 'customers':  if(function_exists('afdp_customers_tab')) afdp_customers_tab(); break;
                    case 'payments':   afdp_payments_tab(); break;
                    case 'shortcodes': afdp_shortcodes_tab(); break;
                    case 'settings':   if(function_exists('afdp_settings_tab')) afdp_settings_tab(); break;
                }
                ?>
            </div>
        </div>
    </div>
    <?php
}

/*--------------------------------------------------------------
# 6. Required File Inclusions
--------------------------------------------------------------*/
require_once AFDP_PATH . 'admin/dashboard.php';
require_once AFDP_PATH . 'admin/orders.php';
require_once AFDP_PATH . 'admin/items.php';
require_once AFDP_PATH . 'admin/categories.php';
require_once AFDP_PATH . 'admin/extras.php';
require_once AFDP_PATH . 'admin/report.php';
require_once AFDP_PATH . 'admin/customers.php';
require_once AFDP_PATH . 'admin/settings.php';
require_once AFDP_PATH . 'admin/shortcodes.php';
require_once AFDP_PATH . 'admin/payments.php';
require_once AFDP_PATH . 'frontend/frontend.php';

/*--------------------------------------------------------------
# 7. Plugin Activation - Auto Create Pages
--------------------------------------------------------------*/
register_activation_hook(__FILE__, 'afdp_plugin_activate');

function afdp_plugin_activate() {
    $pages = [
        'afdp_menu_page' => [
            'title'   => 'Menu',
            'slug'    => 'afdp-menu',
            'content' => '[afdp_food_items]',
        ],
        'afdp_login_page' => [
            'title'   => 'Login',
            'slug'    => 'afdp-login',
            'content' => '[afdp_login]',
        ],
        'afdp_register_page' => [
            'title'   => 'Registration',
            'slug'    => 'afdp-registration',
            'content' => '[afdp_registration]',
        ],
        'afdp_checkout_page' => [
            'title'   => 'Checkout',
            'slug'    => 'afdp-checkout',
            'content' => '[afdp_checkout]',
        ],
        'afdp_account_page' => [
            'title'   => 'Account',
            'slug'    => 'afdp-account',
            'content' => '[afdp_account]',
        ],
        'afdp_thanks_page' => [
            'title'   => 'Thanks',
            'slug'    => 'afdp-thanks',
            'content' => '[afdp_thanks]',
        ],
    ];

    foreach ($pages as $option_key => $page_data) {
        $page_id = get_option($option_key);
        
        // Check if page exists AND is not in the trash
        $page_exists = get_post($page_id);
        $is_trashed  = ($page_exists && $page_exists->post_status === 'trash');

        if (!$page_id || !$page_exists || $is_trashed) {
            $new_page_id = wp_insert_post([
                'post_title'   => $page_data['title'],
                'post_name'    => $page_data['slug'], // Sets the URL slug
                'post_content' => $page_data['content'],
                'post_status'  => 'publish',
                'post_type'    => 'page',
                'post_author'  => 1,
            ]);

            if ($new_page_id && !is_wp_error($new_page_id)) {
                update_option($option_key, $new_page_id);
            }
        }
    }
    
    flush_rewrite_rules();
}

/**
 * Add labels to the WordPress Pages list for easy identification
 */
add_filter('display_post_states', function($post_states, $post) {
    $afdp_pages = [
        'afdp_menu_page'     => __('Menu Page', 'food-delivery-pickup-soluition'),
        'afdp_login_page'    => __('Login Page', 'food-delivery-pickup-soluition'),
        'afdp_register_page' => __('Registration Page', 'food-delivery-pickup-soluition'),
        'afdp_checkout_page' => __('Checkout Page', 'food-delivery-pickup-soluition'),
        'afdp_account_page'  => __('Account Page', 'food-delivery-pickup-soluition'),
        'afdp_thanks_page'   => __('Thanks Page', 'food-delivery-pickup-soluition'),
    ];

    foreach ($afdp_pages as $option_key => $label) {
        if ( (int) get_option($option_key) === $post->ID ) {
            $post_states[$option_key] = $label;
        }
    }

    return $post_states;
}, 10, 2);


/**
 * 1. Global status checker - REINFORCED
 * Ensures site_time is ALWAYS available to prevent PHP warnings.
 */
if ( ! function_exists( 'get_afdp_restaurant_status' ) ) {
    function get_afdp_restaurant_status() {
        // 1. Initial defaults
        $schedule   = get_option('afdp_schedule', []);
        $closed_msg = get_option('afdp_status_message', 'Sorry, we are currently closed!');
        $site_time  = current_time('H:i'); // WordPress native time string
        
        $response = [
            'is_open'   => false,
            'message'   => $closed_msg,
            'site_time' => $site_time // Defined at the very start
        ];

        // 2. Identify current day
        $current_timestamp = current_time('timestamp'); 
        $current_day       = gmdate('D', $current_timestamp); 

        // 3. Validation
        if ( !isset($schedule[$current_day]) || empty($schedule[$current_day]['enabled']) ) {
            return $response;
        }

        $today_data = $schedule[$current_day];
        $open_time  = $today_data['open'];
        $close_time = $today_data['close'];

        // 4. Time Comparison
        if ($site_time >= $open_time && $site_time <= $close_time) {
            $response['is_open'] = true;
            $response['message'] = '';
        }

        return $response;
    }
}

/**
 * 2. Premium Popup - Error Proofed
 */
add_action('wp_footer', 'afdp_premium_closed_popup');

function afdp_premium_closed_popup() {
    if (is_admin()) return;

    $status = get_afdp_restaurant_status();
    
    // Check if open OR if status failed
    if (empty($status) || $status['is_open']) return;

    // Safety fallback for site_time to prevent the "Undefined key" warning
    $display_time = isset($status['site_time']) ? $status['site_time'] : current_time('H:i');

    $schedule   = get_option('afdp_schedule', []);
    $today_key  = gmdate('D', current_time('timestamp'));
    
    $hours_info = (isset($schedule[$today_key]) && $schedule[$today_key]['enabled']) 
        ? $schedule[$today_key]['open'] . ' - ' . $schedule[$today_key]['close']
        : 'Closed Today';
    ?>
    
    <div id="afdp-closed-modal" style="position: fixed; inset: 0; z-index: 9999999; display: flex; align-items: center; justify-content: center; padding: 20px; font-family: 'Plus Jakarta Sans', sans-serif;">
        
        <div style="position: absolute; inset: 0; background: rgba(15, 23, 42, 0.75); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);"></div>
        
        <div class="afdp-glass-modal">
            <div style="padding: 40px 30px; text-align: center;">
                
                <div style="display: inline-flex; align-items: center; background: #0F172A; color: #fff; padding: 6px 14px; border-radius: 12px; font-size: 13px; font-weight: 700; margin-bottom: 25px;">
                    <svg style="margin-right: 8px;" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
                    Store Time: <?php echo esc_html($display_time); ?>
                </div>

                <div class="afdp-icon-circle">
                    <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
                </div>

                <h2 style="margin: 0 0 10px; font-size: 26px; font-weight: 800; color: #0F172A; letter-spacing: -0.8px;">We're Offline</h2>
                
                <p style="margin: 0 0 25px; color: #64748B; font-size: 15px; line-height: 1.6;">
                    <?php echo esc_html($status['message']); ?>
                </p>

                <div style="background: rgba(255,255,255,0.6); border: 1px solid #E2E8F0; border-radius: 20px; padding: 18px; margin-bottom: 30px;">
                    <span style="font-size: 11px; font-weight: 700; color: #94A3B8; text-transform: uppercase; display:block; margin-bottom:5px;">Operating Hours Today</span>
                    <span style="font-size: 18px; font-weight: 800; color: #E11D48;"><?php echo esc_html($hours_info); ?></span>
                </div>

                <button onclick="document.getElementById('afdp-closed-modal').remove()" class="afdp-action-btn">
                    Browse the Menu
                </button>

            </div>
        </div>
    </div>

    <style>
        .afdp-glass-modal {
            position: relative; width: 100%; max-width: 400px;
            background: rgba(255, 255, 255, 0.95); border-radius: 40px;
            box-shadow: 0 40px 100px -20px rgba(0,0,0,0.4);
            animation: afdpPopUp 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }
        .afdp-icon-circle {
            width: 60px; height: 60px; background: #FFF1F2; color: #E11D48;
            border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px;
        }
        .afdp-action-btn {
            width: 100%; padding: 18px; background: #0F172A; color: #fff;
            border: none; border-radius: 20px; font-weight: 700; font-size: 16px;
            cursor: pointer; transition: 0.3s;
        }
        .afdp-action-btn:hover { background: #000; transform: translateY(-2px); }
        @keyframes afdpPopUp {
            from { opacity: 0; transform: scale(0.9) translateY(40px); }
            to { opacity: 1; transform: scale(1) translateY(0); }
        }
    </style>
    <?php
}