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

class Sales_payments extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('sales_payments_model','sales');
	}

	public function index()
	{
		$this->permission_check('sales_payment_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('sales_payments');
		
		// Get customer_id from URL parameter for pre-filtering
		$customer_id = $this->input->get('customer_id');
		$data['preselected_customer_id'] = $customer_id ? $customer_id : '';
		
		$this->load->view('sales_payments/list',$data);
	}


	public function ajax_list()
	{
		$list = $this->sales->get_datatables();
		
		$data = array();
		$no = $_POST['start'];
		foreach ($list as $sales) {
			
			$no++;
			$row = array();
			
			// Checkbox column
			$row[] = '<input type="checkbox" name="checkbox[]" value="'.$sales->id.'" class="column_checkbox" >';
			
			$row[] = $sales->payment_code;
			$row[] = '<span class="editable-date" data-id="'.$sales->id.'" data-field="payment_date" data-value="'.$sales->payment_date.'">'.show_date($sales->payment_date).'</span>';
			
			// Handle sales code - show "Account Payment" if sales_id is null (previous due payment collection)
			if(empty($sales->sales_id)) {
				$row[] = '<span class="label label-info">Account Payment Collection</span>';
			} else {
				$row[] = get_sales_code($sales->sales_id);
			}
			
			// Handle customer details safely
			$customer = get_customer_details($sales->customer_id);
			$row[] = $customer ? $customer->customer_name : 'N/A';
			
			// Split payment into Credit/Debit columns with color coding
			$payment_amount = $sales->payment;
			
			// Credit column (Customer Payments) - Green
			$credit_display = '<span class="editable-amount credit-amount" data-id="'.$sales->id.'" data-field="payment" data-value="'.$payment_amount.'" style="color: #28a745; font-weight: bold;">'.store_number_format($payment_amount).'</span>';
			$row[] = $credit_display;
			
			// Debit column (Sales/Outstanding) - Red - calculated from linked sales
			$debit_amount = 0;
			$bill_amount = 0;
			$debit_display = '-';
			$bill_display = '-';
			$is_credit_invoice = false;
			
			if(!empty($sales->sales_id)) {
				// Get sales amount for this payment
				$sales_info = get_sales_details($sales->sales_id);
				if($sales_info) {
					$debit_amount = $sales_info->grand_total;
					$bill_amount = $sales_info->grand_total;
					$debit_display = '<span style="color: #dc3545; font-weight: bold;">'.store_number_format($debit_amount).'</span>';
					$bill_display = '<span style="font-weight: bold;">'.store_number_format($bill_amount).'</span>';
					
					// Check if this is a credit invoice (payment > bill amount)
					if($payment_amount > $bill_amount) {
						$is_credit_invoice = true;
					}
				}
			}
			$row[] = $debit_display;
			$row[] = $bill_display;


			//$cheque_status = ($sales->cheque_status) ? 'Cleared' : 'Not Cleared';
			$str = (!empty($sales->cheque_number)) ? "<br>Cheque no.:".$sales->cheque_number."<br>Period:".$sales->cheque_period."<br>Status:".
			"<span class='label label-info' style='cursor:pointer'>".$sales->cheque_status."</span>" : '';
			$row[] = ($sales->payment_type).$str;


			$row[] = $sales->payment_note;
			$row[] = ($sales->created_by);

					$str2 = '<div class="btn-group" title="View Account">
										<a class="btn btn-primary btn-o dropdown-toggle" data-toggle="dropdown" href="#">
											Action <span class="caret"></span>
										</a>
										<ul role="menu" class="dropdown-menu dropdown-light pull-right">';
											
											if($this->permissions('sales_payment_add') && strtoupper($sales->payment_type)==strtoupper(cheque_name()))
											$str2.='<li>
												<a title="Update Cheque Status" class="pointer" onclick="update_cheque_status('.$sales->id.')" >
													<i class="fa fa-fw fa-hourglass-half text-blue"></i>Update Cheque Status
												</a>
											</li>';



											if($this->permissions('sales_payment_delete'))
											$str2.='<li>
												<a style="cursor:pointer" title="Delete Record ?" onclick="delete_payment(\''.$sales->id.'\')">
													<i class="fa fa-fw fa-trash text-red"></i>Delete
												</a>
											</li>
											
										</ul>
									</div>';			

			$row[] = $str2;

			// Add row class for credit invoices
			if($is_credit_invoice) {
				$row['DT_RowClass'] = 'credit-invoice-row';
			}

			$data[] = $row;
		}

		$output = array(
						"draw" => $_POST['draw'],
						"recordsTotal" => $this->sales->count_all(),
						"recordsFiltered" => $this->sales->count_filtered(),
						"data" => $data,
				);
		//output to json format
		echo json_encode($output);
	}
	
	
	/*public function multi_delete(){
		$this->permission_check_with_msg('sales_delete');
		$ids=implode (",",$_POST['checkbox']);
		echo $this->sales->delete_payment($ids);
	}*/


	//Table ajax code
	/*public function search_item(){
		$q=$this->input->get('q');
		$result=$this->sales->search_item($q);
		echo $result;
	}
	public function find_item_details(){
		$id=$this->input->post('id');
		
		$result=$this->sales->find_item_details($id);
		echo $result;
	}*/


	public function delete_payment(){
		$this->permission_check_with_msg('sales_payment_delete');
		$payment_id = $this->input->post('payment_id');
		echo $this->sales->delete_payment($payment_id);
	}

	public function multi_delete(){
		$this->permission_check_with_msg('sales_payment_delete');
		$payment_ids = $this->input->post('payment_ids');
		
		if(empty($payment_ids)) {
			echo json_encode(['status' => 'error', 'message' => 'No payments selected']);
			return;
		}
		
		$ids_array = explode(',', $payment_ids);
		$deleted_count = 0;
		
		foreach($ids_array as $payment_id) {
			if(!empty($payment_id)) {
				$result = $this->sales->delete_payment($payment_id);
				$result_data = json_decode($result, true);
				if($result_data['status'] === 'success') {
					$deleted_count++;
				}
			}
		}
		
		if($deleted_count > 0) {
			echo json_encode(['status' => 'success', 'message' => $deleted_count . ' payment(s) deleted successfully']);
		} else {
			echo json_encode(['status' => 'error', 'message' => 'Failed to delete payments']);
		}
	}
	public function show_cheque_payments_modal(){
		$this->permission_check_with_msg('sales_payment_view');
		$payment_id=$this->input->post('payment_id');
		echo $this->sales->show_cheque_payments_modal($payment_id);
	}
	public function update_cheque_payment(){
		$this->permission_check_with_msg('sales_add');
		echo $this->sales->update_cheque_payment();
	}

	// Get payments summary with balances
	public function get_payments_summary(){
		$this->permission_check_with_msg('sales_payment_view');
		$summary = $this->sales->get_payments_summary();
		
		// Format the response for better display - send raw numbers for JavaScript processing
		$response = [
			'success' => true,
			'total_amount' => (float)$summary->total_amount,
			'total_records' => (int)$summary->total_records,
			'linked_sales_count' => (int)$summary->linked_sales_count,
			'total_debit_amount' => (float)$summary->total_debit_amount
		];
		
		// Add opening and closing balances if available
		if(isset($summary->opening_balance)) {
			$response['opening_balance'] = (float)$summary->opening_balance;
		}
		if(isset($summary->closing_balance)) {
			$response['closing_balance'] = (float)$summary->closing_balance;
		}
		
		echo json_encode($response);
	}

	// Update payment amount inline
	public function update_payment_amount(){
		$this->permission_check_with_msg('sales_payment_edit');
		$payment_id = $this->input->post('payment_id');
		$new_amount = $this->input->post('payment_amount');
		echo $this->sales->update_payment_amount($payment_id, $new_amount);
	}

	// Update payment date inline
	public function update_payment_date(){
		$this->permission_check_with_msg('sales_payment_edit');
		$payment_id = $this->input->post('payment_id');
		$new_date = $this->input->post('payment_date');
		echo $this->sales->update_payment_date($payment_id, $new_date);
	}

	// Export detailed report
	public function export_detailed_report(){
		$this->permission_check_with_msg('sales_payment_view');
		
		// Get filter parameters
		$filters = array(
			'customer_search' => $this->input->post('customer_search'),
			'payment_type_search' => $this->input->post('payment_type_search'),
			'cheque_status_search' => $this->input->post('cheque_status_search'),
			'from_date' => $this->input->post('from_date'),
			'to_date' => $this->input->post('to_date'),
			'payment_amount_from' => $this->input->post('payment_amount_from'),
			'payment_amount_to' => $this->input->post('payment_amount_to'),
			'created_by_search' => $this->input->post('created_by_search')
		);
		
		// Get data and summary
		$payments_data = $this->sales->get_export_data($filters);
		$summary_data = $this->sales->get_payments_summary();
		
		// Generate CSV content
		$csv_content = $this->sales->generate_detailed_csv($filters, $payments_data, $summary_data);
		
		// Set headers for download
		header('Content-Type: text/csv');
		header('Content-Disposition: attachment; filename="sales_payments_detailed_report_'.date('Y-m-d').'.csv"');
		header('Pragma: no-cache');
		header('Expires: 0');
		
		echo $csv_content;
	}

	//Print sales Payment Receipt
	
	// Create outstanding balance entries for customers with no payment records
	public function create_outstanding_entries() {
		$this->permission_check('sales_payment_add');
		
		$customer_id = $this->input->post('customer_id'); // Optional filter
		$entry_type = $this->input->post('entry_type'); // 'outstanding' or 'unpaid_invoices'
		
		$created_entries = 0;
		$message = '';
		
		if($entry_type == 'unpaid_invoices') {
			$created_entries = $this->sales->create_unpaid_invoice_entries($customer_id);
			$message = $created_entries . ' unpaid invoice entries created successfully';
		} else {
			$created_entries = $this->sales->create_outstanding_balance_entries($customer_id);
			$message = $created_entries . ' outstanding balance entries created successfully';
		}
		
		if($created_entries > 0) {
			echo json_encode(array(
				'success' => true,
				'message' => $message,
				'entries_created' => $created_entries
			));
		} else {
			echo json_encode(array(
				'success' => false,
				'message' => 'No entries needed - customers already have payment records or no outstanding amounts found',
				'entries_created' => 0
			));
		}
	}

	/*public function print_show_receipt($payment_id){
		if(!$this->permissions('sales_add') && !$this->permissions('sales_edit')){
			$this->show_access_denied_page();
		}
		$data=$this->data;
		$data['page_title']=$this->lang->line('payment_receipt');
		$data=array_merge($data,array('payment_id'=>$payment_id));
		$this->load->view('print-cust-payment-receipt',$data);
	}*/
	
	
	
}
