<?php
/**
 * CRON Job to update AWB records from Resi data
 * Simplified version - only shows success/fail summary
 */

// Database configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'wiselie_nanda');
define('DB_PASS', 'Clemira123');
define('DB_NAME', 'wiselie_inventory');

// Warehouse mapping
$warehouse_map = [
    1 => 'sidoarjo',
    2 => 'jakarta',
    3 => 'makassar',
    4 => 'Bali',
    5 => 'Semarang',
    6 => 'Bandung'
];

// Error reporting - we'll log errors rather than display them
error_reporting(E_ALL);
ini_set('display_errors', 0);

// Initialize summary
$summary = [
    'success' => 0,
    'failed' => 0,
    'skipped' => 0
];

try {
    // Create connection
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    
    // Check connection
    if ($conn->connect_error) {
        throw new Exception("Connection failed: " . $conn->connect_error);
    }
    
    // Set charset to utf8
    if (!$conn->set_charset("utf8mb4")) {
        throw new Exception("Error setting charset: " . $conn->error);
    }

    // Get all resi records that have data to potentially update
    $resi_query = "SELECT resi, scan_in, scan_out, id_packer, id_warehouse FROM resi";
    $resi_result = $conn->query($resi_query);
    
    if ($resi_result === false) {
        throw new Exception("Error fetching resi records: " . $conn->error);
    }
    
    if ($resi_result->num_rows > 0) {
        while ($resi_row = $resi_result->fetch_assoc()) {
            $resi = $conn->real_escape_string($resi_row['resi']);
            $scan_in = $resi_row['scan_in'];
            $scan_out = $resi_row['scan_out'];
            $id_packer = $resi_row['id_packer'];
            $id_warehouse = $resi_row['id_warehouse'];
            
            // Check if this resi exists in awb table
            $awb_check = "SELECT scan_in, scan_status, packer_no, loc FROM awb WHERE resi = '$resi' LIMIT 1";
            $awb_result = $conn->query($awb_check);
            
            if ($awb_result === false || $awb_result->num_rows === 0) {
                $summary['failed']++;
                continue;
            }
            
            $awb_row = $awb_result->fetch_assoc();
            
            // Prepare update parts
            $update_parts = [];
            $needs_update = false;
            
            // Check each field that needs updating
            if (is_null($awb_row['scan_in']) && !is_null($scan_in)) {
                $update_parts[] = "scan_in = '" . $conn->real_escape_string($scan_in) . "'";
                $needs_update = true;
            }
            
            if (is_null($awb_row['scan_status']) && !is_null($scan_out)) {
                $update_parts[] = "scan_status = '" . $conn->real_escape_string($scan_out) . "'";
                $needs_update = true;
            }
            
            if (($awb_row['packer_no'] == 0 || is_null($awb_row['packer_no'])) && !is_null($id_packer)) {
                $update_parts[] = "packer_no = " . intval($id_packer);
                $needs_update = true;
            }
            
            // Check if location needs updating
            if (!is_null($id_warehouse) && isset($warehouse_map[$id_warehouse])) {
                $expected_loc = $warehouse_map[$id_warehouse];
                if (empty($awb_row['loc']) || $awb_row['loc'] != $expected_loc) {
                    $update_parts[] = "loc = '" . $conn->real_escape_string($expected_loc) . "'";
                    $needs_update = true;
                }
            }
            
            if ($needs_update && !empty($update_parts)) {
                // Perform the update
                $update_query = "UPDATE awb SET " . implode(', ', $update_parts) . " WHERE resi = '$resi'";
                if ($conn->query($update_query)) {
                    $summary['success']++;
                } else {
                    $summary['failed']++;
                }
            } else {
                $summary['skipped']++;
            }
        }
    }
    
    // Close connection
    $conn->close();
    
    // Output summary for cron job
    echo "AWB Update Summary:\n";
    echo "Successfully updated: " . $summary['success'] . "\n";
    echo "Failed updates: " . $summary['failed'] . "\n";
    echo "Skipped (no changes needed): " . $summary['skipped'] . "\n";
    
} catch (Exception $e) {
    echo "CRON Job Failed: " . $e->getMessage() . "\n";
    exit(1); // Non-zero exit code indicates error
}

exit(0); // Success