<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../models/AccountingEntry.php';

$database = new Database();
$db = $database->getConnection();

$entry = new AccountingEntry($db);

$request_method = $_SERVER['REQUEST_METHOD'];

switch($request_method) {
    case 'GET':
        if(isset($_GET['id'])) {
            $entry->id = $_GET['id'];
            $entry->readOne();
            
            if($entry->description != null) {
                $entry_arr = array(
                    "id" => $entry->id,
                    "entry_date" => $entry->entry_date,
                    "description" => $entry->description,
                    "entry_type" => $entry->entry_type,
                    "category" => $entry->category,
                    "tax_free_amount" => $entry->tax_free_amount,
                    "vat_percentage" => $entry->vat_percentage,
                    "vat_25_5" => $entry->vat_25_5,
                    "vat_14" => $entry->vat_14,
                    "vat_10" => $entry->vat_10,
                    "total_amount" => $entry->total_amount,
                    "net_amount" => $entry->net_amount,
                    "vat_amount" => $entry->vat_amount,
                    "reference_number" => $entry->reference_number,
                    "entry_type_badge" => $entry->getEntryTypeBadge(),
                    "entry_type_name" => $entry->getEntryTypeName()
                );
                
                http_response_code(200);
                echo json_encode($entry_arr);
            } else {
                http_response_code(404);
                echo json_encode(array("message" => "Entry not found."));
            }
        } else {
            // Handle date range filtering
            if(isset($_GET['start_date']) && isset($_GET['end_date'])) {
                $stmt = $entry->getByDateRange($_GET['start_date'], $_GET['end_date']);
            } else {
                $stmt = $entry->read();
            }
            
            $num = $stmt->rowCount();
            
            if($num > 0) {
                $entries_arr = array();
                $entries_arr["records"] = array();
                
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $entry_item = array(
                        "id" => $row['id'],
                        "entry_date" => $row['entry_date'],
                        "description" => $row['description'],
                        "entry_type" => $row['entry_type'],
                        "category" => $row['category'],
                        "tax_free_amount" => $row['tax_free_amount'],
                        "vat_percentage" => $row['vat_percentage'],
                        "vat_25_5" => $row['vat_25_5'],
                        "vat_14" => $row['vat_14'],
                        "vat_10" => $row['vat_10'],
                        "total_amount" => $row['total_amount'],
                        "net_amount" => $row['net_amount'],
                        "vat_amount" => $row['vat_amount'],
                        "reference_number" => $row['reference_number'],
                        "entry_type_badge" => $entry->getEntryTypeBadge($row['entry_type']),
                        "entry_type_name" => $entry->getEntryTypeName($row['entry_type'])
                    );
                    
                    array_push($entries_arr["records"], $entry_item);
                }
                
                http_response_code(200);
                echo json_encode($entries_arr);
            } else {
                http_response_code(200);
                echo json_encode(array("records" => array()));
            }
        }
        break;
        
    case 'POST':
        $data = json_decode(file_get_contents("php://input"));
        
        if(!empty($data->description) && !empty($data->entry_type)) {
            $entry->entry_date = $data->entry_date ?? date('Y-m-d');
            $entry->description = $data->description;
            $entry->entry_type = $data->entry_type;
            $entry->category = $data->category ?? '';
            $entry->tax_free_amount = $data->tax_free_amount ?? 0;
            $entry->vat_percentage = $data->vat_percentage ?? 0;
            $entry->vat_25_5 = $data->vat_25_5 ?? 0;
            $entry->vat_14 = $data->vat_14 ?? 0;
            $entry->vat_10 = $data->vat_10 ?? 0;
            $entry->total_amount = $data->total_amount ?? 0;
            $entry->net_amount = $data->net_amount ?? 0;
            $entry->vat_amount = $data->vat_amount ?? 0;
            $entry->reference_number = $data->reference_number ?? '';
            
            if($entry->create()) {
                http_response_code(201);
                echo json_encode(array("message" => "Entry was created."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to create entry."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to create entry. Data is incomplete."));
        }
        break;
        
    case 'PUT':
        $data = json_decode(file_get_contents("php://input"));
        
        if(!empty($data->id) && !empty($data->description) && !empty($data->entry_type)) {
            $entry->id = $data->id;
            $entry->entry_date = $data->entry_date ?? date('Y-m-d');
            $entry->description = $data->description;
            $entry->entry_type = $data->entry_type;
            $entry->category = $data->category ?? '';
            $entry->tax_free_amount = $data->tax_free_amount ?? 0;
            $entry->vat_percentage = $data->vat_percentage ?? 0;
            $entry->vat_25_5 = $data->vat_25_5 ?? 0;
            $entry->vat_14 = $data->vat_14 ?? 0;
            $entry->vat_10 = $data->vat_10 ?? 0;
            $entry->total_amount = $data->total_amount ?? 0;
            $entry->net_amount = $data->net_amount ?? 0;
            $entry->vat_amount = $data->vat_amount ?? 0;
            $entry->reference_number = $data->reference_number ?? '';
            
            if($entry->update()) {
                http_response_code(200);
                echo json_encode(array("message" => "Entry was updated."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to update entry."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to update entry. Data is incomplete."));
        }
        break;
        
    case 'DELETE':
        if(isset($_GET['id'])) {
            $entry->id = $_GET['id'];
            
            if($entry->delete()) {
                http_response_code(200);
                echo json_encode(array("message" => "Entry was deleted."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to delete entry."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to delete entry. ID is missing."));
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Method not allowed."));
        break;
}
?>
