<?php

namespace Salesloo\Admin;

use \Salesloo\AdminTable\Payments as Payments_Table;
use \Salesloo\Models\Invoice as Invoice_Model;

/**
 * Admin invoice Page classes
 */
class Invoice
{
    public function template()
    {
        $list_table = new Payments_Table();
        $list_table->prepare_items();
        include SALESLOO_PATH . 'assets/partials/payments-list.php';
    }

    /**
     * handle mark invoice status changed
     *
     * @return mixed
     */
    public function mark_invoice_status()
    {
        global $wpdb;

        if (!isset($_REQUEST['__nonce'])) {
            wp_die('No nonce');
        }

        // verifi nonce
        if (!wp_verify_nonce($_REQUEST['__nonce'], 'mark-invocice-status')) {
            wp_die('invalid');
        }

        $status = isset($_REQUEST['status']) ? strtolower(sanitize_text_field($_REQUEST['status'])) : '';
        $invoice_id = isset($_REQUEST['id']) ? absint($_REQUEST['id']) : 0;

        salesloo_update_invoice_status($invoice_id, $status);

        $redirect = admin_url('admin.php?page=salesloo-invoice');
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

        if ($paged > 1) {
            $redirect = $redirect . '&paged=' . $paged;
        }
        wp_redirect($redirect);
        exit;
    }

    /**
     * change invoice status to cancelled when due date is reached
     *
     * @return void
     */
    public function make_invoice_cancelled()
    {
        $unpaid_invoices = Invoice_Model::select('salesloo_invoice.ID')->query(
            'WHERE status = %s AND due_date_at IS NOT NULL AND due_date_at <= %s',
            'unpaid',
            date('Y-m-d H:i:s')
        )->get();

        if ($unpaid_invoices->found() > 0) {
            foreach ($unpaid_invoices as $invoice) {
                salesloo_update_invoice_status($invoice->ID, 'cancelled');
            }
        }
    }

    /**
     * generate_reminder_notification on unpaid invoice
     *
     * @return void
     */
    public function generate_reminder_notification()
    {
        global $wpdb;

        $checked_date = get_option('salesloo_invoice_unpaid_generate_reminder_date');
        if ($checked_date != date('y-m-d')) {
            update_option('salesloo_invoice_unpaid_generate_reminder_date', date('y-m-d'));
            update_option('salesloo_invoice_unpaid_generate_reminder_paged', 1);
        }

        $checked_paged = intval(get_option('salesloo_invoice_unpaid_generate_reminder_paged'));
        if (!$checked_paged) {
            $checked_paged = 1;
        }

        $query = $wpdb->get_results("SELECT * FROM $wpdb->options WHERE option_name LIKE 'salesloo_notification_email_invoice_unpaid_reminder_%' AND option_value = 1");

        foreach ((array)$query as $option) {
            $day = str_replace('salesloo_notification_email_invoice_unpaid_reminder_', '', $option->option_name);
            $day = intval($day);

            if ($day) {
                $unpaid_invoices = Invoice_Model::select('ID')
                    ->query(
                        'WHERE status = %s AND DATE(DATE_ADD(created_at, INTERVAL +%d DAY)) = %s',
                        'unpaid',
                        $day,
                        date('Y-m-d')
                    )->paginate(100, $checked_paged)->get();

                if ($unpaid_invoices->found() > 0) {
                    foreach ($unpaid_invoices as $invoice) {
                        $data = [
                            'invoice_id' => $invoice->ID,
                            'days_to' => $day
                        ];

                        salesloo_add_notification('invoice_unpaid_reminder', $data);
                        salesloo_add_event('invoice_unpaid_reminder', $data);
                    }
                }
            }
        }

        $checked_paged = $checked_paged + 1;
        update_option('salesloo_invoice_unpaid_generate_reminder_paged', $checked_paged);
    }

    public function export_invoices()
    {
        $nonce = isset($_REQUEST['nonce']) ? $_REQUEST['nonce'] : '';
        if (!wp_verify_nonce($nonce, 'salesloo')) exit;

        $invoices = Invoice_Model::paginate(10000, 1)->get();

        $delimiter = ",";
        $upload_dir   = wp_upload_dir();
        $filename = "salesloo-invoice-data-" . strtotime('now') . ".csv";

        // Create a file pointer 
        $f = fopen($upload_dir['basedir'] . '/' . $filename, 'w');

        $fields = array('Date', 'Invoice Number', 'Customer Name', 'Customer Email', 'Customer Phone', 'Product', 'Total', 'Payment Method', 'Status');
        fputcsv($f, $fields, $delimiter);
        foreach ($invoices as $invoice) {
            $user = get_userdata($invoice->user_id);
            $summary = maybe_unserialize($invoice->summary);
            $products = [];
            foreach ($summary['products'] as $p) {
                $products[] = $p['label'];
            }
            $lineData = [
                $invoice->created_at,
                $invoice->number,
                $user->first_name . ' ' . $user->last_name,
                $user->user_email,
                \get_user_meta($user->ID, 'phone', true),
                implode(',', $products),
                $summary['total']['value'],
                $invoice->payment_method,
                $invoice->status

            ];
            fputcsv($f, $lineData, $delimiter);
        }

        $response['url'] = site_url() . '/wp-content/uploads/' . $filename;
        echo json_encode($response);
        exit;
    }

    public function install_hooks()
    {
        add_action('wp_ajax_mark-invocice-status', [$this, 'mark_invoice_status']);
        add_action('wp_ajax_export-invoices', [$this, 'export_invoices']);

        add_action('salesloo/cron/hourly', [$this, 'make_invoice_cancelled']);
        add_action('salesloo/cron/hourly', [$this, 'generate_reminder_notification']);
    }
}
