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

class Dispute extends CI_Controller {
    function __construct()
 	{
	    parent::__construct();
		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->library('session');
		$this->load->model('common');
		$this->load->database();
		$this->load->library(array('form_validation','template'));
	}

	public function index()   
	{
		$data["disputesData"] = $this->common->readdatafromcollectionwhereclause("Disputes");
		$this->template->template_render('dispute', $data); 
	}

//updatedisputedata
	public function updatedisputedata($id){

		$data["promotions"] = $this->common->updatedatamodel("Disputes",$id,$this->input->post());
		$this->session->set_flashdata('successmessage', 'Disputes has been updated successfully');

		redirect('dispute');
	}

	
	public function deletedispute($id)   
	{
		$this->common->deletedatamodel("Disputes", $id);
		$this->session->set_flashdata('successmessage', 'Disputes Deleted');
		redirect('dispute');
	}
	
public function editDispute($id){


		$data['id']=$id;
		
		$data["reminderdetails"] = $this->common->readdatadocument("Disputes",$id);
		
		 $this->template->template_render('editDispute', $data);


	}


	public function addDispute()   
	{
		$response = $this->common->adddatamodel("Disputes", $this->input->post('ticketNo'), $this->input->post());
 		if ($response) {
 			$this->session->set_flashdata('successmessage', 'Dispute Added Successfuly');
 		} else {
 			$this->session->set_flashdata('warningmessage', 'Error! Something went wrong');
 		}
		redirect('dispute'); 			
	}

	public function resolveDispute($id)   
	{
		$post = $this->input->post();
		$resolutionNotes = isset($post['resolutionNotes']) ? trim($post['resolutionNotes']) : '';
		$refundAmount = isset($post['refundAmount']) ? floatval($post['refundAmount']) : 0;
		$approveRefund = isset($post['approveRefund']) ? true : false;
		
		$data = array(
			"status" => "resolved",
			"resolvedAt" => time() * 1000,
			"resolvedBy" => isset($this->session->userdata['session_data']['u_id']) ? $this->session->userdata['session_data']['u_id'] : 'admin',
			"resolutionNotes" => $resolutionNotes,
			"refundApproved" => $approveRefund,
			"refundAmount" => $refundAmount
		);
		
		$response = $this->common->updatedatamodel("Disputes", $id, $data);
		
		// If refund is approved, process refund
		if ($approveRefund && $refundAmount > 0) {
			// Get dispute details to find associated order
			$dispute = $this->common->readdatadocument("Disputes", $id);
			if (!empty($dispute) && isset($dispute['orderId'])) {
				// Update order with refund information
				$orderUpdate = array(
					'refunded' => true,
					'refundAmount' => $refundAmount,
					'refundDate' => time() * 1000,
					'refundReason' => 'Dispute resolution: ' . $resolutionNotes
				);
				$this->common->updatedatamodel("Orders", $dispute['orderId'], $orderUpdate);
				
				// Here you would typically integrate with Stripe or payment processor to issue actual refund
				// For now, we just mark it in the database
			}
		}
		
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Dispute Resolved Successfully');
		} else {
			$this->session->set_flashdata('warningmessage', 'Error! Something went wrong');
		}
		redirect('dispute'); 			
	}

	/**
	 * Add comment/message to dispute for communication
	 */
	public function addDisputeComment($id)
	{
		$post = $this->input->post();
		$comment = isset($post['comment']) ? trim($post['comment']) : '';
		$commenterRole = isset($post['commenterRole']) ? trim($post['commenterRole']) : 'admin';
		$commenterId = isset($post['commenterId']) ? trim($post['commenterId']) : '';
		
		if (empty($comment)) {
			if ($this->input->is_ajax_request()) {
				echo json_encode(array('success' => false, 'message' => 'Comment cannot be empty'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Comment cannot be empty');
				redirect('dispute/editDispute/' . $id);
				return;
			}
		}
		
		// Get existing dispute
		$dispute = $this->common->readdatadocument("Disputes", $id);
		if (empty($dispute)) {
			if ($this->input->is_ajax_request()) {
				echo json_encode(array('success' => false, 'message' => 'Dispute not found'));
				return;
			} else {
				$this->session->set_flashdata('warningmessage', 'Dispute not found');
				redirect('dispute');
				return;
			}
		}
		
		// Initialize comments array if not exists
		if (!isset($dispute['comments']) || !is_array($dispute['comments'])) {
			$dispute['comments'] = array();
		}
		
		// Add new comment
		$newComment = array(
			'comment' => $comment,
			'commenterRole' => $commenterRole,
			'commenterId' => $commenterId,
			'commenterName' => isset($post['commenterName']) ? trim($post['commenterName']) : 'Admin',
			'createdAt' => time() * 1000
		);
		
		$dispute['comments'][] = $newComment;
		$dispute['lastUpdated'] = time() * 1000;
		
		$response = $this->common->updatedatamodel("Disputes", $id, $dispute);
		
		if ($this->input->is_ajax_request()) {
			if ($response) {
				echo json_encode(array('success' => true, 'message' => 'Comment added successfully', 'comment' => $newComment));
			} else {
				echo json_encode(array('success' => false, 'message' => 'Failed to add comment'));
			}
			return;
		}
		
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Comment added successfully');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to add comment');
		}
		redirect('dispute/editDispute/' . $id);
	}

	/**
	 * Issue refund for a dispute
	 */
	public function issueRefund($id)
	{
		$post = $this->input->post();
		$refundAmount = isset($post['refundAmount']) ? floatval($post['refundAmount']) : 0;
		
		if ($refundAmount <= 0) {
			$this->session->set_flashdata('warningmessage', 'Invalid refund amount');
			redirect('dispute/editDispute/' . $id);
			return;
		}
		
		// Get dispute details
		$dispute = $this->common->readdatadocument("Disputes", $id);
		if (empty($dispute)) {
			$this->session->set_flashdata('warningmessage', 'Dispute not found');
			redirect('dispute');
			return;
		}
		
		// Update dispute with refund information
		$disputeUpdate = array(
			'refundApproved' => true,
			'refundAmount' => $refundAmount,
			'refundDate' => time() * 1000,
			'refundIssuedBy' => isset($this->session->userdata['session_data']['u_id']) ? $this->session->userdata['session_data']['u_id'] : 'admin'
		);
		
		$response = $this->common->updatedatamodel("Disputes", $id, $disputeUpdate);
		
		// Update associated order if exists
		if (isset($dispute['orderId'])) {
			$orderUpdate = array(
				'refunded' => true,
				'refundAmount' => $refundAmount,
				'refundDate' => time() * 1000,
				'refundReason' => 'Dispute refund issued'
			);
			$this->common->updatedatamodel("Orders", $dispute['orderId'], $orderUpdate);
		}
		
		// Here you would typically integrate with Stripe or payment processor to issue actual refund
		// For now, we just mark it in the database
		
		if ($response) {
			$this->session->set_flashdata('successmessage', 'Refund issued successfully');
		} else {
			$this->session->set_flashdata('warningmessage', 'Failed to issue refund');
		}
		redirect('dispute/editDispute/' . $id);
	}	
	
}
