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

class Payments extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->require_login();
		$this->load->model('Payment_model', 'payments');
		$this->load->model('Order_model', 'orders');
	}

	public function create($order_id)
	{
		$this->_handle_save($order_id);
	}

	public function edit($payment_id)
	{
		$payment = $this->payments->find($payment_id);
		if (!$payment) {
			show_404();
		}
		$this->_handle_save($payment->order_id, $payment_id);
	}

	private function _handle_save($order_id, $payment_id = null)
	{
		if ($this->input->method(TRUE) !== 'POST') {
			show_error('Metode tidak diizinkan', 405);
		}

		$this->form_validation->set_rules('amount', 'Nominal', 'required|numeric|greater_than[0]');
		$this->form_validation->set_rules('method', 'Metode', 'trim|required|max_length[30]');
		$this->form_validation->set_rules('note', 'Catatan', 'trim|max_length[255]');

		if (!$this->form_validation->run()) {
			$this->session->set_flashdata('error', validation_errors());
			redirect('orders/show/' . (int) $order_id);
		}

		$data = array(
			'order_id' => (int) $order_id,
			'amount' => (float) $this->input->post('amount', TRUE),
			'method' => $this->input->post('method', TRUE),
			'note' => $this->input->post('note', TRUE),
		);

		$this->db->trans_start();
		if ($payment_id) {
			$this->payments->update($payment_id, $data);
			$msg = 'Pembayaran berhasil diubah.';
		} else {
			$this->payments->create($data);
			$msg = 'Pembayaran berhasil ditambahkan.';
		}
		$this->orders->refresh_paid_amount($order_id);
		$this->db->trans_complete();

		$this->session->set_flashdata('success', $msg);
		redirect('orders/show/' . (int) $order_id);
	}
}

