<?php
/**
 * Fixed Sales Controller - Improved Error Handling
 * This file provides fixes for common POS saving issues
 */

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

class Sales_Fixed extends CI_Controller {
    
    public function __construct(){
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
        $this->load->library('session');
    }
    
    /**
     * Test endpoint to verify controller accessibility
     */
    public function test_connection() {
        echo json_encode([
            'status' => 'success',
            'message' => 'Sales controller is accessible',
            'timestamp' => date('Y-m-d H:i:s')
        ]);
    }
    
    /**
     * Fixed invoice method with proper error handling
     */
    public function invoice($id = null) {
        try {
            // Validate sales ID
            if (!$id || !is_numeric($id) || $id <= 0) {
                show_error("Invalid sales ID", 400, "Bad Request");
                return;
            }
            
            // Check if sales record exists
            $this->db->where('id', $id);
            $sales_exists = $this->db->get('db_sales')->num_rows();
            
            if ($sales_exists == 0) {
                show_error("Sales record not found", 404, "Record Not Found");
                return;
            }
            
            // Check store access (if applicable)
            $this->db->select('store_id');
            $this->db->where('id', $id);
            $sales_record = $this->db->get('db_sales')->row();
            
            if ($sales_record) {
                // If user is logged in, check store access
                if ($this->session->userdata('logged_in')) {
                    $current_store_id = $this->session->userdata('store_id') ?: 1;
                    if ($sales_record->store_id != $current_store_id) {
                        show_error("Access denied to this sales record", 403, "Access Denied");
                        return;
                    }
                }
            }
            
            // Load the invoice view
            $data = array(
                'sales_id' => $id,
                'page_title' => 'Sales Invoice',
                'base_url' => base_url()
            );
            
            $this->load->view('sal-invoice', $data);
            
        } catch (Exception $e) {
            log_message('error', 'Sales invoice error: ' . $e->getMessage());
            show_error("An error occurred while loading the invoice", 500, "Internal Server Error");
        }
    }
    
    /**
     * Fixed sales save method with comprehensive error handling
     */
    public function sales_save_and_update() {
        try {
            // Enable error reporting for debugging
            error_reporting(E_ALL);
            ini_set('display_errors', 1);
            
            // Set JSON header
            header('Content-Type: application/json');
            
            // Validate required fields
            $required_fields = ['sales_date', 'customer_id'];
            $missing_fields = array();
            
            foreach ($required_fields as $field) {
                if (empty($this->input->post($field))) {
                    $missing_fields[] = $field;
                }
            }
            
            if (!empty($missing_fields)) {
                echo json_encode([
                    'status' => 'failed',
                    'message' => 'Missing required fields: ' . implode(', ', $missing_fields)
                ]);
                return;
            }
            
            // Validate customer exists
            $customer_id = $this->input->post('customer_id');
            $this->db->where('id', $customer_id);
            $customer_exists = $this->db->get('db_customers')->num_rows();
            
            if ($customer_exists == 0) {
                echo json_encode([
                    'status' => 'failed',
                    'message' => 'Invalid customer selected'
                ]);
                return;
            }
            
            // Start transaction
            $this->db->trans_start();
            
            // Prepare sales data
            $sales_data = array(
                'sales_date' => $this->input->post('sales_date'),
                'customer_id' => $customer_id,
                'sales_status' => $this->input->post('sales_status') ?: 'Final',
                'warehouse_id' => $this->input->post('warehouse_id') ?: 1,
                'store_id' => $this->session->userdata('store_id') ?: 1,
                'reference_no' => $this->input->post('reference_no') ?: '',
                'subtotal' => $this->input->post('tot_subtotal_amt') ?: 0,
                'grand_total' => $this->input->post('tot_total_amt') ?: 0,
                'other_charges_amt' => $this->input->post('other_charges_amt') ?: 0,
                'discount_to_all_amt' => $this->input->post('tot_discount_to_all_amt') ?: 0,
                'round_off' => $this->input->post('tot_round_off_amt') ?: 0,
                'payment_status' => 'Unpaid',
                'paid_amount' => 0,
                'created_date' => date('Y-m-d'),
                'created_time' => date('H:i:s'),
                'created_by' => $this->session->userdata('username') ?: 'system',
                'system_ip' => $this->input->ip_address(),
                'status' => 1
            );
            
            // Handle command (save or update)
            $command = $this->input->get('command') ?: 'save';
            $sales_id = null;
            
            if ($command == 'update') {
                $sales_id = $this->input->post('sales_id');
                if (!$sales_id) {
                    echo json_encode([
                        'status' => 'failed',
                        'message' => 'Sales ID required for update'
                    ]);
                    return;
                }
                
                $this->db->where('id', $sales_id);
                $this->db->update('db_sales', $sales_data);
            } else {
                // Generate sales code
                $init_code = $this->input->post('init_code') ?: 'SL';
                $count_id = $this->get_next_count_id();
                $sales_code = $init_code . str_pad($count_id, 4, '0', STR_PAD_LEFT);
                
                $sales_data['init_code'] = $init_code;
                $sales_data['count_id'] = $count_id;
                $sales_data['sales_code'] = $sales_code;
                
                $this->db->insert('db_sales', $sales_data);
                $sales_id = $this->db->insert_id();
            }
            
            if (!$sales_id) {
                echo json_encode([
                    'status' => 'failed',
                    'message' => 'Failed to save sales record'
                ]);
                return;
            }
            
            // Process sales items
            $this->process_sales_items($sales_id);
            
            // Complete transaction
            $this->db->trans_complete();
            
            if ($this->db->trans_status() === FALSE) {
                echo json_encode([
                    'status' => 'failed',
                    'message' => 'Database transaction failed'
                ]);
                return;
            }
            
            echo json_encode([
                'status' => 'success',
                'sales_id' => $sales_id,
                'message' => 'Sales record saved successfully'
            ]);
            
        } catch (Exception $e) {
            log_message('error', 'Sales save error: ' . $e->getMessage());
            echo json_encode([
                'status' => 'failed',
                'message' => 'System error: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * Process sales items
     */
    private function process_sales_items($sales_id) {
        $rowcount = $this->input->get('rowcount') ?: 0;
        
        if ($rowcount > 0) {
            // Clear existing items for update
            $this->db->where('sales_id', $sales_id);
            $this->db->delete('db_salesitems');
            
            for ($i = 1; $i <= $rowcount; $i++) {
                $item_id = $this->input->post("td_data_{$i}_1");
                $qty = $this->input->post("td_data_{$i}_3");
                $price = $this->input->post("td_data_{$i}_4");
                
                if ($item_id && $qty > 0) {
                    $item_data = array(
                        'sales_id' => $sales_id,
                        'item_id' => $item_id,
                        'sales_qty' => $qty,
                        'price_per_unit' => $price ?: 0,
                        'total_cost' => ($qty * ($price ?: 0)),
                        'status' => 1
                    );
                    
                    $this->db->insert('db_salesitems', $item_data);
                }
            }
        }
    }
    
    /**
     * Get next count ID for sales
     */
    private function get_next_count_id() {
        $this->db->select_max('count_id');
        $query = $this->db->get('db_sales');
        $max_count = $query->row()->count_id;
        return ($max_count ? $max_count + 1 : 1);
    }
    
    /**
     * Debug method to check system status
     */
    public function debug_status() {
        $status = array(
            'database_connected' => $this->db->initialize(),
            'session_active' => $this->session->userdata('logged_in') ? true : false,
            'base_url' => base_url(),
            'current_time' => date('Y-m-d H:i:s'),
            'php_version' => PHP_VERSION,
            'codeigniter_version' => CI_VERSION
        );
        
        // Test database tables
        $tables = ['db_sales', 'db_customers', 'db_items', 'db_salesitems'];
        foreach ($tables as $table) {
            try {
                $result = $this->db->query("SHOW TABLES LIKE '{$table}'")->num_rows();
                $status['tables'][$table] = $result > 0 ? 'exists' : 'missing';
            } catch (Exception $e) {
                $status['tables'][$table] = 'error: ' . $e->getMessage();
            }
        }
        
        header('Content-Type: application/json');
        echo json_encode($status, JSON_PRETTY_PRINT);
    }
}
?>
