<?php 

// session_start();

require_once("../../../config.php");
require ABSPATH.'app/lib/phpspreadsheet/vendor/autoload.php';
ini_set('max_execution_time', 300);
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Protection;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
require_once("../../../app/functions.php");
require_once("../../../app/table-functions.php");
// require_once("../../../app/includes/phpmailer/class.phpmailer.php");
spl_autoload_register(function($class_name) {
	$file = "../../../app/classes/class-".$class_name.".php";
	if (file_exists($file)) {
		include $file;
	}
});

require_once("../plugins.php");
$plugins = new plugins();
$plugins->load();

$session = Session::getInstance();

if ($_SERVER["REQUEST_METHOD"] == "POST") :

	if(isset($_POST['action'])){
		$response = array();
		$args = sanitize($_POST);
		unset($args['action']);
		$user = new user;
		$post = new post;
		$support = new support(['software_engineer', 'super_admin']);

		switch ($_POST['action']) {

			case 'school_fees_set_up':
				if(empty($args['class'])) {
					$response['msg'] = "Sorry, you did not select any class. Please add classes.";
					$response['error'] = 1;
					echo json_encode($response);
					exit();
				}
				if(!isset($args['items'])) {
					$response['error'] = 1;
					$response['msg'] = "You must add at least one item to the invoice.";
					echo json_encode($response);
					exit();
				}
				if($args['gender'] === 'Both') {
					$args['gender'] = ['Male', 'Female'];
				} else {
					$args['gender'] = [$args['gender']];
				}
				foreach ($args['items']['description'] as $key => $value) {
					$deadline = ($args['items']['deadline'][$key] !== "") ? strtotime($args['items']['deadline'][$key]) : "";
					foreach ($args['class'] as $class) {
						set_time_limit(30);
						$class = explode(",", $class);
						foreach ($args['gender'] as $gender) {
							$meta['description'] = $args['items']['description'][$key];
							$meta['narration'] = $args['items']['narration'][$key];
							$meta['amount'] = $args['items']['unit_price'][$key];
							$meta['quantity'] = $args['items']['qty'][$key];
							$meta['class'] = $class[0];
							$meta['category'] = $class[1];
							$meta['term'] = $args['term'];
							$meta['gender'] = $gender;
							$meta['deadline'] = $deadline;
							$meta['type'] = 'sfm_fee';
							$meta['status'] = 'Pending';
							if($existing = db_post_unique(['type' => 'sfm_fee', 'description' => $args['items']['description'][$key], 'class' => $class[0], 'category' => $class[1], 'term' => $args['term'], 'gender' => $gender])) {
								$post->update_post_meta($existing['id'], $meta);
							} else {
								$post->add_post($meta);
							}
						}
						
					}
				}
				$response['msg'] = "Fees recorded successfully";
				$response['error'] = 0;
				$response['args'] = $args;
				echo json_encode($response);
				exit();
				break;

			case 'add_fee_description':
				if(db_post_unique(['type' => 'sfm_description', 'description' => $args['description']])) {
					$response['msg'] = "Sorry, you have have already added this description before";
					$response['error'] = 1;
				} else {
					$args['type'] = "sfm_description";
					$args['status'] = 'active';
					$args['added_by'] = $session->id;
					$post->add_post($args);
					admin_log("Added ".$args['description']." fee description");
					$response['msg'] = "Description was added successfully";
					$response['error'] = 0;
				}
				echo json_encode($response);
				exit();
				break;

			case 'edit_fee_description':
				if($existing = db_post_unique(['type' => 'sfm_description', 'description' => $args['description']])) {
					if($existing['id'] != $args['id']) {
						$response['msg'] = "Sorry, you have have already added this description before";
						$response['error'] = 1;
						echo json_encode($response);
						exit();
					}
				} 
				$args['last_edited_by'] = $session->id;
				$post->update_post_meta($args['id'], $args);
				admin_log("Edited ".$args['description']." fee description");
				$response['msg'] = "Description was edited successfully";
				$response['error'] = 0;
				echo json_encode($response);
				exit();
				break;

			case "sfm_get_term_fee":
				$q = ['type' => "sfm_fee", "term" => $args['term']];
				$desc = $post->get_post_by_meta_data($q, 'LIKE', false, 0, 0, 'post_id', 'DESC');
				$table = new table("materials-table", $desc);
			    $table->set_display_columns([
			    	"sn" => "SN",
			        "class" => "Class",
			        "gender" => "Gender",
			        "narration" => "Description",
			        "amount" => "Amount",
			        "deadline" => "Deadline",
			        "status" => "Status"
			    ]);
			    $table->set_dynamic_columns([
			    	"class" => "_tf_eedu_display_student_class",
			    	"deadline" => "_tf_get_date"
			    ]);
		    	$table->set_action_links([
		    		"Send Invoice" => false,
		    		"Delete" => false
			    ]);
			    $table->set_action_access([
			    	"Send Invoice" => "sfm_send_fee_invoice",
			    	"Delete" => "delete_post"
			    ]);
			    $table->set_action_callback([
			    	"Send Invoice" => "sfm_send_fee_invoice",
			    	"Delete" => "delete_post"
			    ]);
			    $table->set_action_condition([
			    	"Send Invoice" => ["status" => "Pending"]
			    ]);
			    $table->set_action_conditioner([
			    	"Send Invoice" => ["status" => "=="]
			    ]);
			    $table->set_action_args([
			    	"Send Invoice" => ["id" => "id", "callback" => "sfm_getTermFees", "callbackid" => "#display"],
			    	"Delete" => ["id" => "id", "callback" => "sfm_getTermFees", "callbackid" => "#display"]
			    ]);
			    $response = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case "sfm_get_term_fee_student":
				$q = ['type' => "sfm_fee", "term" => $args['term']];
				$class = get_student_class_in_term($args['student_id'], $args['term']);
				$student = $user->get_user_meta($args['student_id']);
				$q['class'] = $class['class_id'];
				$q['category'] = $class['category_id'];
				$gender = isset($student['gender']) ? $student['gender'] : "";
				switch (strtolower($gender)) {
					case 'male':
					case 'm':
					case '':
					case 'boy':
					case 'man':
						$q['gender'] = "Male";
						break;

					case 'female':
					case 'f':
					case 'woman':
					case 'girl':
						$q['gender'] = "Female";
						break;
					
					default:
						$q['gender'] = "Male";
						break;
				}
				$desc = $post->get_post_by_meta_data($q, 'LIKE', false, 0, 0, 'post_id', 'DESC');
				$table = new table("materials-table", $desc);
				$table->student = $student;
			    $table->set_display_columns([
			    	"sn" => "SN",
			        "class" => "Class",
			        "gender" => "Gender",
			        "narration" => "Description",
			        "amount" => "Amount",
			        "deadline" => "Deadline",
			        "inv_status" => "Status"
			    ]);
			    $table->set_dynamic_columns([
			    	"class" => "_tf_eedu_display_student_class",
			    	"inv_status" => "_tf_sfm_check_fee_status_student",
			    	"deadline" => "_tf_get_date"
			    ]);
		    	// $table->set_action_links([
		    	// 	"Send Invoice" => false,
		    	// 	"Delete" => false
			    // ]);
			    // $table->set_action_access([
			    // 	"Send Invoice" => "sfm_send_fee_invoice",
			    // 	"Delete" => "delete_post"
			    // ]);
			    // $table->set_action_callback([
			    // 	"Send Invoice" => "sfm_send_fee_invoice",
			    // 	"Delete" => "delete_post"
			    // ]);
			    // $table->set_action_condition([
			    // 	"Send Invoice" => ["status" => "Pending"]
			    // ]);
			    // $table->set_action_conditioner([
			    // 	"Send Invoice" => ["status" => "=="]
			    // ]);
			    // $table->set_action_args([
			    // 	"Send Invoice" => ["id" => "id", "callback" => "sfm_getTermFees", "callbackid" => "#display"],
			    // 	"Delete" => ["id" => "id", "callback" => "sfm_getTermFees", "callbackid" => "#display"]
			    // ]);
			    $response = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case "sfm_get_fee_description":
				$desc = $post->get_post_by_meta_data(['type' => "sfm_description"]);
				$table = new table("materials-table", $desc);
			    $table->set_display_columns([
			        "id" => "ID",
			        "description" => "Description",
			        "status" => "Status"
			    ]);
		    	$table->set_action_links([
		    		"Edit" => "sfm-edit-fee-description"
			    ]);
			    $table->set_action_access([
			    	"Edit" => 'sfm_edit_fee_description'
			    ]);
			    $table->set_action_callback([
			    	"Edit" => false
			    ]);
			    $table->set_action_condition([
			    	"Edit" => ["id" => get_option("sfm_school_fees")]
			    ]);
			    $table->set_action_conditioner([
			    	"Edit" => ["id" => "!="]
			    ]);
			    $table->set_action_args([
			    	"Edit" => ["id" => "id"]
			    ]);
			    $response = $table->table_html();
				echo json_encode($response);
				exit();
				break;

			case "download_fees_zip":
				// $class = eedu_portal_get_class_selection($args['class_category']);
				$settings = [
					'term' => $args['term'],
					// 'class' => $class['class'],
					// 'category' => $class['category']
				];
				$response['file'] = download_fees_for_all_class($settings);
				$response['time'] = time();
				echo json_encode($response);
				exit();
				break;

			default:
				$response['msg'] = "Sorry, you have not a module ".$_POST['action']." to process this form submission";
				$response['error'] = 1;
				echo json_encode($response);
				exit();
				break;
		}
		// json_encode($response);
	}

endif;