<?php
session_start();

require_once '../Config/Database.php';
require_once '../Model/Payment.php';
require_once '../Model/PaymentType.php';
$payment = new Payment();
$payment_type_obj = new PaymentType();
$payments = $payment->read_all_payments();

if(isset($_GET['all_payments'])){
    echo json_encode(
        array("data"=>$payments)
    ); 
}

if(isset($_POST['add_payment'])){
    $payer = $_POST['payer'];
    $payment_type = $_POST['payment_type'];
    $amount = $_POST['amount'];
    $payment_date = $_POST['payment_date'];
    $data = array(
        "payer"=>$payer,
        "payment_type"=>$payment_type,
        "amount"=>$amount,
        "payment_date"=>$payment_date,
        "entry_by"=>$_SESSION['employee_id']
    );
    $success = $payment->add_payment($data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}

if(isset($_POST['update_payment'])){
    $payment_id = $_POST['payment_id'];
    $payment_type = $_POST['payment_type_name'];
    $amount = $_POST['amount'];
    $payment_date = $_POST['payment_date'];
    $payment_type_details = $payment_type_obj->get_payment_type_by_name($payment_type);
    $payment_type_id = $payment_type_details[0]['payment_type_id'];
    $data = array(
        "payment_type"=>$payment_type_id,
        "amount"=>$amount,
        "payment_date"=>$payment_date
    );
    $key = array(
        "payment_id"=>$payment_id
    );
    $success = $payment->update_payment($key,$data);
    if($success){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}


if(isset($_POST['remove_payment'])){
    $payment_id = $_POST['payment_id'];
    $data = $payment->remove_payment($payment_id);
    if(!$data){
        echo json_encode(
            array('data'=>'success')
        );
    
    }else{
        echo json_encode(
            array('data'=>'fail')
        );
    
    }
}