<?php

require __dir__ . '/init.php';

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	
	$accounts = $settings->get("account_types") ?? [];
	
	if( isset($_POST['action']) ) {
		
		switch( $_POST['action'] ) {
			
			case 'delete':
					$key = (int)$_POST['key'];
					if( array_key_exists($key, $accounts) ) unset($accounts[$key]);
					$accounts = array_values($accounts);
					$status = $settings->set('account_types', $accounts);
					$__msg = $status ? "Account Type Deleted" : "Account Type Not Deleted";
				break;
			
		}
		
	} else {

		$type = strtolower($_POST['account_type']);
		
		if( !in_array($type, $accounts) ) {
			$accounts[] = $type;
			$status = $settings->set("account_types", $accounts);
			$msg = $status ? "Account type added" : "Account type not added";
		} else {
			$status = !($msg = "Cannot add duplicate account type");
		}
		
	};
};

template::get_header();

$accounts = $settings->get('account_types');

?>

	<?php template::title( 'Account Types' ); ?>

	<div class='row'>
		<div class='col-xl-5'>
			<div class='card'>
				<div class='card-body'>
				
					<?php template::alert( $msg, $status ?? null ); ?>
					
					<form method='post'>
					
						<div class='mb-2'>
							<label class='form-label'>Account Type</label>
							<input type='text' class='form-control' name='account_type' placeholder='e.g savings account' required>
						</div>
						
						<div class='mb-2'>
							<button class='btn btn-primary btn-block'>Add</button>
						</div>
						
					</form>
				</div>
			</div>
		</div>
		<div class='col-xl-7'>
			<div class='card'>
				<div class='card-body'>
					
					<?php template::alert( $__msg ?? null, $status ?? null ); ?>
					
					<div class='table-responsive'>
						<table class='table table-hover' data-table='simple'>
							<thead>
								<tr>
									<th>Account Type</th>
									<th></th>
								</tr>
							</thead>
							<tbody>
								<?php 
									if( !empty($accounts) ):
										foreach( $accounts as $key => $value ):
								?>
									<tr>
										<th><?php echo ucwords($value); ?></th>
										<th class='text-right'>
											<form method='post' onsubmit="return confirm('Click OK to confirm');">
												<input type='hidden' name='key' value='<?php echo $key; ?>'>
												<button class='btn btn-danger' name='action' value='delete'>
													<i class='fas fa-trash'></i>
												</button>
											</form>
										</th>
									</tr>
								<?php 
										endforeach; 
									endif;
								?>
							</tbody>
						</table>
					</div>
					
					<?php if( empty($accounts) ): ?>
					
						<div class='alert alert-info'>
							No account type added yet!
						</div>
					
					<?php endif; ?>
					
				</div>
			</div>
		</div>
	</div>

<?php template::get_footer(); 