<?php
/**
 * Expiry Notification Cron Job
 * 
 * This script should be run daily via cron to check for expiring items
 * and send notifications. Add this to your crontab:
 * 
 * # Run expiry notifications daily at 9 AM
 * 0 9 * * * /usr/bin/php /path/to/your/project/application/cron/expiry_notifications.php
 */

// Set the path to your CodeIgniter installation
$system_path = dirname(dirname(__DIR__)) . '/index.php';

// Load CodeIgniter
require_once $system_path;

// Get CodeIgniter instance
$CI =& get_instance();

// Load required models
$CI->load->model('expiry_notification_model');

// Set timezone
date_default_timezone_set('UTC');

// Log start
log_message('info', 'Starting expiry notification cron job');

try {
    // Send expiry notifications
    $notifications_sent = $CI->expiry_notification_model->send_expiry_notifications();
    
    log_message('info', "Expiry notification cron job completed. Notifications sent: {$notifications_sent}");
    
    // Optional: Send email summary to admin
    $this->send_admin_summary($notifications_sent);
    
} catch (Exception $e) {
    log_message('error', 'Expiry notification cron job failed: ' . $e->getMessage());
}

/**
 * Send email summary to admin (optional)
 */
function send_admin_summary($notifications_sent) {
    $CI =& get_instance();
    
    // Get admin email from settings
    $CI->db->select('setting_value');
    $CI->db->from('db_system_settings');
    $CI->db->where('setting_key', 'company_email');
    $admin_email = $CI->db->get()->row();
    
    if ($admin_email && !empty($admin_email->setting_value)) {
        $CI->load->library('email');
        
        $CI->email->from('noreply@yourcompany.com', 'POS System');
        $CI->email->to($admin_email->setting_value);
        $CI->email->subject('Daily Expiry Notification Summary');
        $CI->email->message("Expiry notifications sent today: {$notifications_sent}");
        
        $CI->email->send();
    }
}
