<?php
/**
 * Sales Controller PHP 8+ Compatible Version
 * Fixes the "Failed to save Record" issue for newer PHP versions
 */

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

class Sales_php8_compatible extends CI_Controller {
    
    public function __construct(){
        parent::__construct();
        
        // Set error reporting for PHP 8+ compatibility
        if (PHP_MAJOR_VERSION >= 8) {
            error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE);
            ini_set('display_errors', 0);
            ini_set('log_errors', 1);
        }
        
        $this->load->database();
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->library('form_validation');
    }
    
    /**
     * PHP 8+ Compatible Sales Save and Update
     */
    public function sales_save_and_update() {
        try {
            // Set response headers
            header('Content-Type: text/plain; charset=utf-8');
            
            // PHP 8+ safe input retrieval
            $sales_date = $this->input->post('sales_date') ?? '';
            $customer_id = $this->input->post('customer_id') ?? '';
            $sales_status = $this->input->post('sales_status') ?? 'Final';
            $count_id = $this->input->post('count_id') ?? '';
            
            // Validation with PHP 8+ compatibility
            if (empty($sales_date)) {
                echo "failed<<<###>>>Sales date is required";
                return;
            }
            
            if (empty($customer_id) || !is_numeric($customer_id)) {
                echo "failed<<<###>>>Valid customer is required";
                return;
            }
            
            if (empty($count_id) || !is_numeric($count_id)) {
                echo "failed<<<###>>>Count ID is required";
                return;
            }
            
            // Get command safely
            $command = $this->input->get('command') ?? 'save';
            
            // Get totals safely with PHP 8+ null coalescing
            $subtotal_amt = (float)($this->input->get('tot_subtotal_amt') ?? 0);
            $discount_amt = (float)($this->input->get('tot_discount_to_all_amt') ?? 0);
            $round_off_amt = (float)($this->input->get('tot_round_off_amt') ?? 0);
            $total_amt = (float)($this->input->get('tot_total_amt') ?? 0);
            $other_charges_amt = (float)($this->input->get('other_charges_amt') ?? 0);
            $coupon_discount_amt = (float)($this->input->get('coupon_discount_amt') ?? 0);
            $rowcount = (int)($this->input->get('rowcount') ?? 0);
            
            // Check if at least one item is added
            $has_items = false;
            for ($i = 1; $i <= $rowcount; $i++) {
                $item_qty = $this->input->post("td_data_{$i}_3");
                if (!empty($item_qty) && is_numeric($item_qty) && $item_qty > 0) {
                    $has_items = true;
                    break;
                }
            }
            
            if (!$has_items) {
                echo "failed<<<###>>>Please add at least one item";
                return;
            }
            
            // Start database transaction
            $this->db->trans_start();
            
            // Prepare sales data with PHP 8+ safe assignments
            $sales_data = array(
                'sales_date' => $sales_date,
                'customer_id' => (int)$customer_id,
                'sales_status' => $sales_status,
                'warehouse_id' => (int)($this->input->post('warehouse_id') ?? 1),
                'store_id' => (int)($this->session->userdata('store_id') ?? 1),
                'reference_no' => $this->input->post('reference_no') ?? '',
                'subtotal' => $subtotal_amt,
                'other_charges_amt' => $other_charges_amt,
                'discount_to_all_amt' => $discount_amt,
                'round_off' => $round_off_amt,
                'grand_total' => $total_amt,
                'coupon_discount_amt' => $coupon_discount_amt,
                'payment_status' => 'Unpaid',
                'paid_amount' => 0.00,
                'pos' => 1, // Mark as POS transaction
                'created_date' => date('Y-m-d'),
                'created_time' => date('H:i:s'),
                'created_by' => $this->session->userdata('username') ?? 'system',
                'system_ip' => $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1',
                'system_name' => gethostname() ?? 'localhost',
                'status' => 1
            );
            
            $sales_id = null;
            
            if ($command === 'update') {
                // Update existing sales record
                $sales_id = (int)($this->input->post('sales_id') ?? 0);
                if ($sales_id <= 0) {
                    echo "failed<<<###>>>Invalid sales ID for update";
                    return;
                }
                
                $this->db->where('id', $sales_id);
                $update_result = $this->db->update('db_sales', $sales_data);
                
                if (!$update_result) {
                    echo "failed<<<###>>>Failed to update sales record";
                    return;
                }
                
                // Delete existing sales items for update
                $this->db->where('sales_id', $sales_id);
                $this->db->delete('db_salesitems');
                
            } else {
                // Create new sales record
                $init_code = $this->input->post('init_code') ?? 'SL';
                $sales_code = $init_code . str_pad($count_id, 4, '0', STR_PAD_LEFT);
                
                $sales_data['init_code'] = $init_code;
                $sales_data['count_id'] = (int)$count_id;
                $sales_data['sales_code'] = $sales_code;
                
                $insert_result = $this->db->insert('db_sales', $sales_data);
                
                if (!$insert_result) {
                    echo "failed<<<###>>>Failed to create sales record";
                    return;
                }
                
                $sales_id = $this->db->insert_id();
            }
            
            // Insert sales items with PHP 8+ compatibility
            $items_inserted = 0;
            for ($i = 1; $i <= $rowcount; $i++) {
                $item_id = $this->input->post("td_data_{$i}_1");
                $item_qty = $this->input->post("td_data_{$i}_3");
                $item_price = $this->input->post("td_data_{$i}_4");
                $item_total = $this->input->post("td_data_{$i}_6");
                
                // PHP 8+ safe validation
                if (!empty($item_id) && is_numeric($item_id) && 
                    !empty($item_qty) && is_numeric($item_qty) && $item_qty > 0) {
                    
                    $item_data = array(
                        'sales_id' => $sales_id,
                        'item_id' => (int)$item_id,
                        'sales_qty' => (float)$item_qty,
                        'price_per_unit' => (float)($item_price ?? 0),
                        'total_cost' => (float)($item_total ?? 0),
                        'status' => 1
                    );
                    
                    $item_insert = $this->db->insert('db_salesitems', $item_data);
                    if ($item_insert) {
                        $items_inserted++;
                    }
                }
            }
            
            if ($items_inserted === 0) {
                echo "failed<<<###>>>No valid items were added";
                return;
            }
            
            // Handle payment if provided
            $payment_amount = (float)($this->input->post('amount') ?? 0);
            $payment_type = $this->input->post('payment_type') ?? '';
            
            if ($payment_amount > 0 && !empty($payment_type)) {
                $payment_data = array(
                    'sales_id' => $sales_id,
                    'payment_date' => $sales_date,
                    'payment_type' => $payment_type,
                    'payment' => $payment_amount,
                    'customer_id' => (int)$customer_id,
                    'created_date' => date('Y-m-d'),
                    'created_time' => date('H:i:s'),
                    'status' => 1
                );
                
                $this->db->insert('db_salespayments', $payment_data);
                
                // Update sales record with payment info
                $this->db->where('id', $sales_id);
                $this->db->update('db_sales', array(
                    'paid_amount' => $payment_amount,
                    'payment_status' => ($payment_amount >= $total_amt) ? 'Paid' : 'Partial'
                ));
            }
            
            // Complete transaction
            $this->db->trans_complete();
            
            if ($this->db->trans_status() === FALSE) {
                echo "failed<<<###>>>Database transaction failed";
                return;
            }
            
            // Success response
            echo "success<<<###>>>{$sales_id}";
            
        } catch (Throwable $e) {
            // PHP 8+ compatible exception handling
            error_log("Sales save error: " . $e->getMessage());
            echo "failed<<<###>>>System error occurred";
        }
    }
    
    /**
     * PHP 8+ Compatible Invoice View
     */
    public function invoice($id = null) {
        // Validate sales ID with PHP 8+ strict typing
        if (!$id || !is_numeric($id) || (int)$id <= 0) {
            show_error("Invalid sales ID", 400, "Bad Request");
            return;
        }
        
        $sales_id = (int)$id;
        
        // Check if sales record exists
        $this->db->where('id', $sales_id);
        $sales_query = $this->db->get('db_sales');
        
        if ($sales_query->num_rows() === 0) {
            show_error("Sales record not found", 404, "Record Not Found");
            return;
        }
        
        // Load invoice view with safe data
        $data = array(
            'sales_id' => $sales_id,
            'page_title' => 'Sales Invoice',
            'base_url' => base_url()
        );
        
        $this->load->view('sal-invoice', $data);
    }
    
    /**
     * Test endpoint for debugging
     */
    public function test_php8_compatibility() {
        header('Content-Type: application/json');
        
        $status = array(
            'php_version' => PHP_VERSION,
            'php_major_version' => PHP_MAJOR_VERSION,
            'database_connected' => $this->db->initialize(),
            'session_active' => $this->session->userdata('logged_in') ? true : false,
            'timestamp' => date('Y-m-d H:i:s'),
            'memory_usage' => memory_get_usage(true),
            'server_software' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'
        );
        
        // Test database
        try {
            $test_query = $this->db->query("SELECT 1 as test");
            $status['database_test'] = $test_query ? 'success' : 'failed';
        } catch (Throwable $e) {
            $status['database_test'] = 'error: ' . $e->getMessage();
        }
        
        echo json_encode($status, JSON_PRETTY_PRINT);
    }
}
?>
