<?php

namespace Unlockafe_Addons\Classes;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

class Cart_Abandonment
{
    private $table_name;

    public function __construct()
    {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'unlockafe_abandoned_carts';

        add_action('init', [$this, 'init_hooks']);
        add_action('unlockafe_abandoned_cart_check', [$this, 'check_for_abandoned_carts']);

        register_activation_hook(UNLOCKAFE_ADDONS_BASE, [$this, 'schedule_cron']);
        register_deactivation_hook(UNLOCKAFE_ADDONS_BASE, [$this, 'unschedule_cron']);
    }

    public function init_hooks() {
        add_action('woocommerce_cart_updated', [$this, 'track_cart']);
        add_action('woocommerce_checkout_process', [$this, 'capture_guest_email']);
        add_action('woocommerce_checkout_order_processed', [$this, 'delete_cart_on_order_completion'], 10, 1);
    }

    public function track_cart() {
        if (!function_exists('WC') || WC()->cart === null) return;

        $session_id = WC()->session->get_customer_id();
        $cart = WC()->cart->get_cart();

        if (empty($cart)) {
            $this->delete_cart($session_id);
            return;
        }

        $user_id = get_current_user_id();
        $user_email = null;
        if ($user_id) {
            $user_info = get_userdata($user_id);
            $user_email = $user_info->user_email;
        } else {
            $user_email = WC()->session->get('guest_email');
        }

        $data = [
            'user_id' => $user_id ? $user_id : null,
            'user_email' => $user_email,
            'cart_contents' => maybe_serialize($cart),
            'cart_total' => WC()->cart->get_total('edit'),
            'currency' => get_woocommerce_currency(),
            'status' => 'abandoned',
            'updated_at' => current_time('mysql'),
            'session_id' => $session_id
        ];

        $this->insert_or_update_cart($data);
    }

    public function capture_guest_email() {
        if (!is_user_logged_in() && !empty($_POST['billing_email'])) {
            WC()->session->set('guest_email', sanitize_email($_POST['billing_email']));
            // Re-run track_cart to update the record with the email
            $this->track_cart();
        }
    }

    private function insert_or_update_cart($data) {
        global $wpdb;

        $existing_cart = $wpdb->get_row($wpdb->prepare(
            "SELECT id FROM {$this->table_name} WHERE session_id = %s",
            $data['session_id']
        ));

        if ($existing_cart) {
            // Update
            $wpdb->update($this->table_name, $data, ['id' => $existing_cart->id]);
        } else {
            // Insert
            $data['created_at'] = current_time('mysql');
            $wpdb->insert($this->table_name, $data);
        }
    }

    public function delete_cart_on_order_completion($order_id) {
        $order = wc_get_order($order_id);
        if ($order) {
            $session_id = $order->get_customer_id();
            $this->delete_cart($session_id);
        }
    }

    private function delete_cart($session_id) {
        global $wpdb;
        $wpdb->delete($this->table_name, ['session_id' => $session_id]);
    }

    public function schedule_cron()
    {
        if (!wp_next_scheduled('unlockafe_abandoned_cart_check')) {
            wp_schedule_event(time(), 'hourly', 'unlockafe_abandoned_cart_check');
        }
    }

    public function unschedule_cron()
    {
        wp_clear_scheduled_hook('unlockafe_abandoned_cart_check');
    }

    public function check_for_abandoned_carts()
    {
        global $wpdb;
        $abandoned_time = time() - 3600; // 1 hour ago

        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$this->table_name} WHERE status = 'abandoned' AND updated_at < %s AND user_email IS NOT NULL AND recovery_email_sent_at IS NULL",
            date('Y-m-d H:i:s', $abandoned_time)
        ));

        foreach ($results as $cart) {
            $coupon_code = $this->generate_recovery_coupon($cart->user_email);
            if ($coupon_code) {
                $this->send_recovery_email($cart, $coupon_code);
                $wpdb->update($this->table_name, 
                    ['recovery_email_sent_at' => current_time('mysql')], 
                    ['id' => $cart->id]
                );
            }
        }
    }

    private function generate_recovery_coupon($email)
    {
        $coupon_code = 'RECOVER-' . wp_generate_password(8, false);
        $coupon = new \WC_Coupon();
        $coupon->set_code($coupon_code);
        $coupon->set_discount_type('percent');
        $coupon->set_amount(10); // 10% discount
        $coupon->set_individual_use(true);
        $coupon->set_usage_limit(1);
        $coupon->set_expiry_date(strtotime('+7 days'));
        $coupon->set_email_restrictions([$email]);
        $coupon->save();

        return $coupon_code;
    }

    private function send_recovery_email($cart, $coupon_code)
    {
        $to = $cart->user_email;
        $subject = 'You left something in your cart!';
        $mailer = WC()->mailer();
        
        // You should create a proper email template for this
        $message = "Hello,\n\nWe noticed you left some items in your cart. To help you complete your purchase, here is a 10% discount coupon: " . $coupon_code . "\n\nThis coupon expires in 7 days.";
        
        $email = new \WC_Email();
        $email->set_recipient($to);
        $email->set_heading($subject);
        $email->set_subject($subject);
        $email->send($subject, $email->style_inline($mailer->wrap_message($subject, $message)), [], '');
    }
}
