<?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/Invoice.php';
require_once __DIR__ . '/../models/InvoiceItem.php';

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

$invoice = new Invoice($db);
$invoiceItem = new InvoiceItem($db);

$request_method = $_SERVER['REQUEST_METHOD'];

switch($request_method) {
    case 'GET':
        if(isset($_GET['id'])) {
            $invoice->id = $_GET['id'];
            $invoice->readOne();
            
            if($invoice->invoice_number != null) {
                $invoice_arr = array(
                    "id" => $invoice->id,
                    "client_id" => $invoice->client_id,
                    "invoice_number" => $invoice->invoice_number,
                    "issue_date" => $invoice->issue_date,
                    "due_date" => $invoice->due_date,
                    "status" => $invoice->status,
                    "subtotal" => $invoice->subtotal,
                    "tax_amount" => $invoice->tax_amount,
                    "total_amount" => $invoice->total_amount,
                    "notes" => $invoice->notes,
                    "created_at" => $invoice->created_at,
                    "updated_at" => $invoice->updated_at,
                    "client_name" => $invoice->getClientName()
                );
                
                $invoice_arr['items'] = $invoice->getInvoiceItems($invoice->id);
                $invoice_arr['payments'] = $invoice->getPayments($invoice->id);
                
                http_response_code(200);
                echo json_encode($invoice_arr);
            } else {
                http_response_code(404);
                echo json_encode(array("message" => "Invoice not found."));
            }
        } elseif(isset($_GET['client_id'])) {
            $invoice->client_id = $_GET['client_id'];
            $stmt = $invoice->read();
            $num = $stmt->rowCount();
            
            if($num > 0) {
                $invoices_arr = array();
                $invoices_arr["records"] = array();
                
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    extract($row);
                    
                    $invoice_item = array(
                        "id" => $id,
                        "client_id" => $client_id,
                        "invoice_number" => $invoice_number,
                        "issue_date" => $issue_date,
                        "due_date" => $due_date,
                        "status" => $status,
                        "subtotal" => $subtotal,
                        "tax_amount" => $tax_amount,
                        "total_amount" => $total_amount,
                        "notes" => $notes,
                        "created_at" => $created_at,
                        "updated_at" => $updated_at,
                        "client_name" => $client_name
                    );
                    
                    array_push($invoices_arr["records"], $invoice_item);
                }
                
                http_response_code(200);
                echo json_encode($invoices_arr);
            } else {
                http_response_code(200);
                echo json_encode(array("records" => array()));
            }
        } else {
            $stmt = $invoice->read();
            $num = $stmt->rowCount();
            
            if($num > 0) {
                $invoices_arr = array();
                $invoices_arr["records"] = array();
                
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    extract($row);
                    
                    $invoice_item = array(
                        "id" => $id,
                        "client_id" => $client_id,
                        "invoice_number" => $invoice_number,
                        "issue_date" => $issue_date,
                        "due_date" => $due_date,
                        "status" => $status,
                        "subtotal" => $subtotal,
                        "tax_amount" => $tax_amount,
                        "total_amount" => $total_amount,
                        "notes" => $notes,
                        "created_at" => $created_at,
                        "updated_at" => $updated_at,
                        "client_name" => $client_name
                    );
                    
                    array_push($invoices_arr["records"], $invoice_item);
                }
                
                http_response_code(200);
                echo json_encode($invoices_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->client_id) && !empty($data->invoice_number) && !empty($data->issue_date) && !empty($data->due_date)) {
            $invoice->client_id = $data->client_id;
            $invoice->invoice_number = $data->invoice_number;
            $invoice->issue_date = $data->issue_date;
            $invoice->due_date = $data->due_date;
            $invoice->status = $data->status ?? 'draft';
            $invoice->subtotal = $data->subtotal ?? 0;
            $invoice->tax_amount = $data->tax_amount ?? 0;
            $invoice->total_amount = $data->total_amount ?? 0;
            $invoice->notes = $data->notes ?? '';
            
            if($invoice->create()) {
                http_response_code(201);
                echo json_encode(array("message" => "Invoice was created."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to create invoice."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to create invoice. Data is incomplete."));
        }
        break;
        
    case 'PUT':
        $data = json_decode(file_get_contents("php://input"));
        
        if(!empty($data->id) && !empty($data->client_id) && !empty($data->invoice_number) && !empty($data->issue_date) && !empty($data->due_date)) {
            $invoice->id = $data->id;
            $invoice->client_id = $data->client_id;
            $invoice->invoice_number = $data->invoice_number;
            $invoice->issue_date = $data->issue_date;
            $invoice->due_date = $data->due_date;
            $invoice->status = $data->status;
            $invoice->subtotal = $data->subtotal ?? 0;
            $invoice->tax_amount = $data->tax_amount ?? 0;
            $invoice->total_amount = $data->total_amount ?? 0;
            $invoice->notes = $data->notes ?? '';
            
            if($invoice->update()) {
                http_response_code(200);
                echo json_encode(array("message" => "Invoice was updated."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to update invoice."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to update invoice. Data is incomplete."));
        }
        break;
        
    case 'DELETE':
        if(isset($_GET['id'])) {
            $invoice->id = $_GET['id'];
            
            if($invoice->delete()) {
                http_response_code(200);
                echo json_encode(array("message" => "Invoice was deleted."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to delete invoice."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to delete invoice. ID is missing."));
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Method not allowed."));
        break;
}
?>
