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

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

$journalEntry = new JournalEntry($db);
$accountTransaction = new AccountTransaction($db);

$request_method = $_SERVER['REQUEST_METHOD'];

switch($request_method) {
    case 'GET':
        if(isset($_GET['id'])) {
            $journalEntry->id = $_GET['id'];
            $journalEntry->readOne();
            
            if($journalEntry->entry_number != null) {
                $entry_arr = array(
                    "id" => $journalEntry->id,
                    "entry_number" => $journalEntry->entry_number,
                    "entry_date" => $journalEntry->entry_date,
                    "description" => $journalEntry->description,
                    "reference_number" => $journalEntry->reference_number,
                    "created_at" => $journalEntry->created_at,
                    "updated_at" => $journalEntry->updated_at,
                    "transactions" => $journalEntry->getTransactions($journalEntry->id)
                );
                
                http_response_code(200);
                echo json_encode($entry_arr);
            } else {
                http_response_code(404);
                echo json_encode(array("message" => "Journal entry not found."));
            }
        } else {
            $stmt = $journalEntry->read();
            $num = $stmt->rowCount();
            
            if($num > 0) {
                $entries_arr = array();
                $entries_arr["records"] = array();
                
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    extract($row);
                    
                    $entry_item = array(
                        "id" => $id,
                        "entry_number" => $entry_number,
                        "entry_date" => $entry_date,
                        "description" => $description,
                        "reference_number" => $reference_number,
                        "created_at" => $created_at,
                        "updated_at" => $updated_at
                    );
                    
                    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->entry_date)) {
            $journalEntry->entry_number = $data->entry_number ?? $journalEntry->generateEntryNumber();
            $journalEntry->entry_date = $data->entry_date;
            $journalEntry->description = $data->description ?? '';
            $journalEntry->reference_number = $data->reference_number ?? '';
            
            if($journalEntry->create()) {
                $entry_id = $this->conn->lastInsertId();
                
                // Create account transactions if provided
                if(isset($data->transactions) && is_array($data->transactions)) {
                    foreach($data->transactions as $transaction) {
                        $accountTransaction->journal_entry_id = $entry_id;
                        $accountTransaction->account_id = $transaction->account_id;
                        $accountTransaction->debit_amount = $transaction->debit_amount ?? 0;
                        $accountTransaction->credit_amount = $transaction->credit_amount ?? 0;
                        $accountTransaction->description = $transaction->description ?? '';
                        
                        if(!$accountTransaction->create()) {
                            http_response_code(503);
                            echo json_encode(array("message" => "Unable to create account transaction."));
                            return;
                        }
                    }
                }
                
                http_response_code(201);
                echo json_encode(array("message" => "Journal entry was created."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to create journal entry."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to create journal entry. Entry date is required."));
        }
        break;
        
    case 'PUT':
        $data = json_decode(file_get_contents("php://input"));
        
        if(!empty($data->id) && !empty($data->entry_date)) {
            $journalEntry->id = $data->id;
            $journalEntry->entry_number = $data->entry_number;
            $journalEntry->entry_date = $data->entry_date;
            $journalEntry->description = $data->description ?? '';
            $journalEntry->reference_number = $data->reference_number ?? '';
            
            if($journalEntry->update()) {
                // Update account transactions if provided
                if(isset($data->transactions) && is_array($data->transactions)) {
                    // Delete existing transactions for this entry
                    $delete_query = "DELETE FROM account_transactions WHERE journal_entry_id = ?";
                    $delete_stmt = $this->conn->prepare($delete_query);
                    $delete_stmt->bindParam(1, $data->id);
                    $delete_stmt->execute();
                    
                    // Create new transactions
                    foreach($data->transactions as $transaction) {
                        $accountTransaction->journal_entry_id = $data->id;
                        $accountTransaction->account_id = $transaction->account_id;
                        $accountTransaction->debit_amount = $transaction->debit_amount ?? 0;
                        $accountTransaction->credit_amount = $transaction->credit_amount ?? 0;
                        $accountTransaction->description = $transaction->description ?? '';
                        
                        if(!$accountTransaction->create()) {
                            http_response_code(503);
                            echo json_encode(array("message" => "Unable to create account transaction."));
                            return;
                        }
                    }
                }
                
                http_response_code(200);
                echo json_encode(array("message" => "Journal entry was updated."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to update journal entry."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to update journal entry. Data is incomplete."));
        }
        break;
        
    case 'DELETE':
        if(isset($_GET['id'])) {
            $journalEntry->id = $_GET['id'];
            
            if($journalEntry->delete()) {
                http_response_code(200);
                echo json_encode(array("message" => "Journal entry was deleted."));
            } else {
                http_response_code(503);
                echo json_encode(array("message" => "Unable to delete journal entry."));
            }
        } else {
            http_response_code(400);
            echo json_encode(array("message" => "Unable to delete journal entry. ID is missing."));
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(array("message" => "Method not allowed."));
        break;
}
?>
