<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Reminder Controller
 * Handles reminder processing and report display
 */
class Reminder extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Reminder_model');
        $this->load->library('email');
        $this->load->helper('url');
    }

    /**
     * CLI endpoint for processing reminders
     * Called by Windows Task Scheduler daily at 9 AM
     * 
     * Usage: php index.php reminder process_reminders
     */
    public function process_reminders()
    {
        // Allow CLI access only or with special key
        if (!$this->input->is_cli_request() && $this->input->get('key') !== 'dms_reminder_cron_2026') {
            show_error('Access denied', 403);
            return;
        }

        log_message('info', '=== REMINDER CRON STARTED ===');
        echo "=== REMINDER CRON STARTED: " . date('Y-m-d H:i:s') . " ===\n";

        try {
            // Get all pending reminders
            $reminders = $this->Reminder_model->getPendingReminders();
            
            log_message('info', 'Found ' . count($reminders) . ' potential reminders');
            echo "Found " . count($reminders) . " potential reminders to process.\n";

            $sent_count = 0;
            $failed_count = 0;
            $skipped_count = 0;

            foreach ($reminders as $reminder) {
                // Get recipients for this reminder
                $recipients = $this->Reminder_model->getRecipients(
                    $reminder['company_id'],
                    $reminder['type_id'],
                    $reminder['authority_id'],
                    $reminder['reminder_to_user'],
                    $reminder['reminder_to_admin'],
                    $reminder['reminder_to_super_admin']
                );

                if (empty($recipients)) {
                    log_message('debug', 'No recipients found for: ' . $reminder['type_name']);
                    continue;
                }

                foreach ($recipients as $recipient) {
                    // Send Email
                    if (!empty($recipient['email'])) {
                        // Check if already sent
                        if ($this->Reminder_model->isReminderSent(
                            $reminder['company_id'],
                            $reminder['type_id'],
                            $recipient['user_id'],
                            $reminder['document_month'],
                            $reminder['document_year'],
                            $reminder['days_before'],
                            'email'
                        )) {
                            $skipped_count++;
                            continue;
                        }

                        $result = $this->sendEmailReminder($reminder, $recipient);
                        
                        // Log the reminder
                        $this->Reminder_model->logReminder([
                            'company_id' => $reminder['company_id'],
                            'type_id' => $reminder['type_id'],
                            'authority_id' => $reminder['authority_id'],
                            'user_id' => $recipient['user_id'],
                            'reminder_type' => 'email',
                            'recipient_email' => $recipient['email'],
                            'recipient_name' => $recipient['name'],
                            'recipient_role' => $recipient['role'],
                            'document_month' => $reminder['document_month'],
                            'document_year' => $reminder['document_year'],
                            'due_date' => $reminder['due_date'],
                            'days_before_due' => $reminder['days_before'],
                            'status' => $result['success'] ? 'sent' : 'failed',
                            'error_message' => $result['error'] ?? null
                        ]);

                        if ($result['success']) {
                            $sent_count++;
                            echo "✓ Email sent to {$recipient['email']} for {$reminder['type_name']}\n";
                        } else {
                            $failed_count++;
                            echo "✗ Email failed to {$recipient['email']}: {$result['error']}\n";
                        }
                    }

                    // Send WhatsApp
                    if (!empty($recipient['phone'])) {
                        // Check if already sent
                        if ($this->Reminder_model->isReminderSent(
                            $reminder['company_id'],
                            $reminder['type_id'],
                            $recipient['user_id'],
                            $reminder['document_month'],
                            $reminder['document_year'],
                            $reminder['days_before'],
                            'whatsapp'
                        )) {
                            $skipped_count++;
                            continue;
                        }

                        // Log WhatsApp reminder as pending (manual sending required via web)
                        $this->Reminder_model->logReminder([
                            'company_id' => $reminder['company_id'],
                            'type_id' => $reminder['type_id'],
                            'authority_id' => $reminder['authority_id'],
                            'user_id' => $recipient['user_id'],
                            'reminder_type' => 'whatsapp',
                            'recipient_phone' => $recipient['phone'],
                            'recipient_name' => $recipient['name'],
                            'recipient_role' => $recipient['role'],
                            'document_month' => $reminder['document_month'],
                            'document_year' => $reminder['document_year'],
                            'due_date' => $reminder['due_date'],
                            'days_before_due' => $reminder['days_before'],
                            'status' => 'pending',
                            'error_message' => 'WhatsApp requires manual sending via web interface'
                        ]);

                        echo "→ WhatsApp logged for {$recipient['phone']} (requires manual sending)\n";
                    }
                }
            }

            $summary = "=== SUMMARY ===\n";
            $summary .= "Sent: {$sent_count}\n";
            $summary .= "Failed: {$failed_count}\n";
            $summary .= "Skipped (already sent): {$skipped_count}\n";
            
            echo $summary;
            log_message('info', str_replace("\n", " | ", $summary));

        } catch (Exception $e) {
            log_message('error', 'Reminder cron error: ' . $e->getMessage());
            echo "ERROR: " . $e->getMessage() . "\n";
        }

        echo "=== REMINDER CRON COMPLETED: " . date('Y-m-d H:i:s') . " ===\n";
        log_message('info', '=== REMINDER CRON COMPLETED ===');
    }

    /**
     * Send email reminder
     */
    private function sendEmailReminder($reminder, $recipient)
    {
        try {
            $this->load->config('email');
            
            $this->email->clear();
            $this->email->from(
                $this->config->item('from_email'), 
                $this->config->item('from_name')
            );
            $this->email->to($recipient['email']);
            
            // Determine subject based on days before
            $days = $reminder['days_before'];
            if ($days > 0) {
                $subject = "Reminder: Document Due in {$days} Days - {$reminder['type_name']}";
            } elseif ($days == 0) {
                $subject = "URGENT: Document Due Today - {$reminder['type_name']}";
            } else {
                $subject = "OVERDUE: Document Was Due Yesterday - {$reminder['type_name']}";
            }
            
            $this->email->subject($subject);
            
            // Build email body
            $monthNames = ['', 'January', 'February', 'March', 'April', 'May', 'June', 
                          'July', 'August', 'September', 'October', 'November', 'December'];
            $monthName = $monthNames[$reminder['document_month']];
            
            $body = $this->buildEmailBody($reminder, $recipient, $monthName);
            
            $this->email->message($body);
            
            if ($this->email->send()) {
                return ['success' => true];
            } else {
                return ['success' => false, 'error' => $this->email->print_debugger(['headers', 'subject'])];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    /**
     * Build email body HTML
     */
    private function buildEmailBody($reminder, $recipient, $monthName)
    {
        $days = $reminder['days_before'];
        $urgency = '';
        $color = '#3b82f6';
        
        if ($days > 7) {
            $urgency = 'Upcoming';
            $color = '#3b82f6';
        } elseif ($days > 0) {
            $urgency = 'Due Soon';
            $color = '#f59e0b';
        } elseif ($days == 0) {
            $urgency = 'Due Today';
            $color = '#ef4444';
        } else {
            $urgency = 'OVERDUE';
            $color = '#dc2626';
        }
        
        $uploadUrl = base_url("upload/index/{$reminder['company_id']}?type_id={$reminder['type_id']}&month={$reminder['document_month']}&year={$reminder['document_year']}");
        
        return "
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset='UTF-8'>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background: {$color}; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
                .content { background: #f9fafb; padding: 20px; border: 1px solid #e5e7eb; }
                .footer { background: #f3f4f6; padding: 15px; text-align: center; font-size: 12px; color: #6b7280; border-radius: 0 0 8px 8px; }
                .btn { display: inline-block; background: {$color}; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 15px 0; }
                .detail-row { padding: 8px 0; border-bottom: 1px solid #e5e7eb; }
                .label { font-weight: bold; color: #374151; }
                .badge { display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: bold; background: {$color}; color: white; }
            </style>
        </head>
        <body>
            <div class='container'>
                <div class='header'>
                    <h1 style='margin:0;'>📄 Document Reminder</h1>
                    <p style='margin:5px 0 0 0;'><span class='badge'>{$urgency}</span></p>
                </div>
                <div class='content'>
                    <p>Dear {$recipient['name']},</p>
                    <p>This is a reminder for the following document upload:</p>
                    
                    <div class='detail-row'>
                        <span class='label'>Company:</span> {$reminder['company_name']}
                    </div>
                    <div class='detail-row'>
                        <span class='label'>Authority:</span> {$reminder['authority_name']}
                    </div>
                    <div class='detail-row'>
                        <span class='label'>Document Head:</span> {$reminder['type_name']}
                    </div>
                    <div class='detail-row'>
                        <span class='label'>Period:</span> {$monthName} {$reminder['document_year']}
                    </div>
                    <div class='detail-row'>
                        <span class='label'>Due Date:</span> " . date('d M Y', strtotime($reminder['due_date'])) . "
                    </div>
                    <div class='detail-row'>
                        <span class='label'>Frequency:</span> {$reminder['frequency']}
                    </div>
                    
                    <p style='text-align:center;'>
                        <a href='{$uploadUrl}' class='btn'>📤 Upload Documents Now</a>
                    </p>
                    
                    <p style='color:#6b7280;font-size:14px;'>
                        Please ensure the documents are uploaded before the due date to avoid compliance issues.
                    </p>
                </div>
                <div class='footer'>
                    <p>This is an automated reminder from VML Document Management System.</p>
                    <p>© " . date('Y') . " VML - All rights reserved</p>
                </div>
            </div>
        </body>
        </html>
        ";
    }

    /**
     * Reminder Report Page
     */
    public function report()
    {
        $login_id = $this->session->userdata('id');
        if (!$login_id) {
            redirect('login');
        }

        // Check permission - only admin and super admin
        $role_id = $this->session->userdata('role_id');
        if ($role_id > 2) {
            show_error('Access denied', 403);
            return;
        }

        $this->load->model('Permission_model');
        
        // Get filters
        $filters = [
            'company_id' => $this->input->get('company_id'),
            'type_id' => $this->input->get('type_id'),
            'year' => $this->input->get('year'),
            'month' => $this->input->get('month'),
            'status' => $this->input->get('status'),
            'reminder_type' => $this->input->get('reminder_type'),
            'date_from' => $this->input->get('date_from'),
            'date_to' => $this->input->get('date_to')
        ];

        // For non-super admins, restrict to their companies
        if ($role_id == 2) {
            $allowed_companies = $this->Permission_model->get_user_company_ids($login_id);
            if (!empty($filters['company_id']) && !in_array($filters['company_id'], $allowed_companies)) {
                $filters['company_id'] = null;
            }
        }

        $data['reminders'] = $this->Reminder_model->getReminderReport($filters);
        $data['stats'] = $this->Reminder_model->getReminderStats($filters['company_id']);
        $data['filters'] = $filters;
        
        // Get filter options
        if ($role_id == 1) {
            $data['companies'] = $this->db->where('status', '1')->get('company')->result_array();
        } else {
            $company_ids = $this->Permission_model->get_user_company_ids($login_id);
            $data['companies'] = $this->db->where('status', '1')
                ->where_in('id', $company_ids)
                ->get('company')
                ->result_array();
        }
        
        $data['document_heads'] = $this->db->where('status', '1')->get('sub_type')->result_array();
        $data['current_year'] = date('Y');
        
        $this->load->view('templates/header');
        $this->load->view('reminder/report', $data);
        $this->load->view('layout/footer');
    }

    /**
     * Get pending WhatsApp reminders for manual sending
     */
    public function getPendingWhatsApp()
    {
        $login_id = $this->session->userdata('id');
        if (!$login_id) {
            echo json_encode(['success' => false, 'message' => 'Not logged in']);
            return;
        }

        $company_id = $this->input->get('company_id');
        
        $pending = $this->db->select('
            rl.*,
            c.company_name,
            st.type_name
        ')
        ->from('reminder_logs rl')
        ->join('company c', 'c.id = rl.company_id', 'left')
        ->join('sub_type st', 'st.id = rl.type_id', 'left')
        ->where('rl.reminder_type', 'whatsapp')
        ->where('rl.status', 'pending')
        ->order_by('rl.created_at', 'DESC')
        ->get()
        ->result_array();

        echo json_encode(['success' => true, 'data' => $pending]);
    }

    /**
     * Mark WhatsApp reminder as sent (after manual sending)
     */
    public function markWhatsAppSent()
    {
        $login_id = $this->session->userdata('id');
        if (!$login_id) {
            echo json_encode(['success' => false, 'message' => 'Not logged in']);
            return;
        }

        $id = $this->input->post('id');
        if (!$id) {
            echo json_encode(['success' => false, 'message' => 'Invalid reminder ID']);
            return;
        }

        $this->Reminder_model->updateReminderStatus($id, 'sent');
        echo json_encode(['success' => true, 'message' => 'Marked as sent']);
    }

    /**
     * Test endpoint for sending a test reminder
     */
    public function test_reminder()
    {
        $login_id = $this->session->userdata('id');
        $role_id = $this->session->userdata('role_id');
        
        if (!$login_id || $role_id != 1) {
            show_error('Access denied - Super Admin only', 403);
            return;
        }

        // Get test parameters
        $email = $this->input->get('email');
        if (!$email) {
            echo "Usage: reminder/test_reminder?email=your@email.com";
            return;
        }

        $this->load->config('email');
        
        $this->email->clear();
        $this->email->from(
            $this->config->item('from_email'), 
            $this->config->item('from_name')
        );
        $this->email->to($email);
        $this->email->subject('Test Reminder Email - DMS');
        $this->email->message("
            <h1>Test Reminder</h1>
            <p>This is a test reminder email from the Document Management System.</p>
            <p>If you received this, the reminder system is working correctly.</p>
            <p>Time: " . date('Y-m-d H:i:s') . "</p>
        ");

        if ($this->email->send()) {
            echo "✓ Test email sent successfully to {$email}";
        } else {
            echo "✗ Failed to send test email:\n";
            echo $this->email->print_debugger();
        }
    }
}

