<?php
error_log($_SERVER['REQUEST_METHOD']);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

include 'connection.php';
require 'vendor/autoload.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\ExpiredException;

$secret_key = "1ED495A77B65435D317B3E6582E4C";

// Check DB Connection
if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Connection failed: ' . $conn->connect_error]);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {

    $headers = apache_request_headers();
    $jwt = null;

    if (isset($headers['Authorization'])) {
        if (preg_match('/Bearer\s(\S+)/', $headers['Authorization'], $matches)) {
            $jwt = $matches[1];
        }
    }

    if (!$jwt) {
        echo json_encode(["success" => false, "message" => "Authorization token missing"]);
        exit;
    }

    try {
        // Decode Token
        $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
        $company_id = $decoded->data->companyId;

        if (!isset($_GET['type'])) {
            echo json_encode(["success" => false, "message" => "Type not provided"]);
            exit;
        }

        $type = $_GET['type'];
        $sql = "";
        $bindTypes = "i";
        $bindValues = [$company_id];

        // -----------------------------
        // 🔥 SWITCH CASE (ONLY ONE CASE)
        // -----------------------------
        switch ($type) {

            case 'ledger_trial_sheet':
                    $sql = "
                        SELECT 
                            le.ledger_name,
                            le.acc_type,
                            le.opening,
                            le.ledger_under,
                            DATE_FORMAT(ldw.date, '%b') AS month_name,
                            IFNULL(SUM(ldw.credit), 0) AS total_credit,
                            IFNULL(SUM(ldw.debit), 0) AS total_debit
                        FROM ledger_entry le
                        LEFT JOIN ledger_day_wise ldw 
                            ON le.ledger_name = ldw.ledger 
                            AND le.com_id = ldw.com_id
                        WHERE le.com_id = ?
                          AND le.status = 'Active'
                        GROUP BY le.ledger_name, le.acc_type, le.opening, le.ledger_under, MONTH(ldw.date)
                        ORDER BY le.ledger_name, MONTH(ldw.date)
                    ";
                    break;
                    /*
                     case 'loan_outstanding':
                    $sql = "
                        SELECT
                            ldw.particulars,
                            SUM(ldw.credit) AS total_credit,
                            SUM(ldw.debit) AS total_debit,
                            (SUM(ldw.debit) - SUM(ldw.credit)) AS total_amount
                        FROM 
                            ledger_day_wise ldw
                        WHERE 
                            ldw.com_id = ?
                            AND ldw.voucher_type IN ('Principal', 'Loan')
                        GROUP BY 
                            ldw.particulars
                        ORDER BY 
                            ldw.particulars;
                    ";
                    break;*/
                    
                     case 'loan_outstanding':
                    $sql = "
                                                SELECT
                            DATE(ldw.date) AS trans_date,
                            ldw.particulars,
                            SUM(ldw.credit) AS total_credit,
                            SUM(ldw.debit) AS total_debit,
                            (SUM(ldw.debit) - SUM(ldw.credit)) AS total_amount
                        FROM 
                            ledger_day_wise ldw
                        WHERE 
                            ldw.com_id = ?
                            AND ldw.voucher_type IN ('Principal', 'Loan')
                        GROUP BY 
                            DATE(ldw.date),
                            ldw.particulars
                        ORDER BY 
                            DATE(ldw.date) ASC,
                            ldw.particulars ASC;
                    ";
                    break;
                    

                    case 'capital_acc':
                    $sql = "
                           SELECT
                                ldw.date,
                                ldw.voucher_type,
                                ldw.particulars,
                                SUM(ldw.credit) AS total_credit,
                                SUM(ldw.debit) AS total_debit,
                                (SUM(ldw.debit) - SUM(ldw.credit)) AS total_amount
                            FROM 
                                ledger_day_wise ldw
                            WHERE 
                                ldw.com_id = ?
                                AND ldw.voucher_type IN ('Deposit', 'Capital')
                            GROUP BY 
                                ldw.date,
                                ldw.voucher_type,
                                ldw.particulars
                            ORDER BY 
                                ldw.date,
                                ldw.voucher_type,
                                ldw.particulars;
                    ";
                    break;
                    
                    
                    case 'ledger_balance_sheet':
                                    $sql = "
                                      SELECT 
                                        le.ledger_name,
                                        le.acc_type,
                                        le.opening,
                                        le.ledger_under,
                                        ldw.date AS entry_date, 
                                        DATE_FORMAT(ldw.date, '%b') AS month_name,
                                        IFNULL(SUM(ldw.credit), 0) AS total_credit,
                                        IFNULL(SUM(ldw.debit), 0) AS total_debit
                                    FROM ledger_entry le
                                    LEFT JOIN ledger_day_wise ldw 
                                        ON le.ledger_name = ldw.ledger 
                                        AND le.com_id = ldw.com_id
                                    WHERE le.com_id = ?
                                      AND le.status = 'Active'
                                    GROUP BY 
                                        le.ledger_name, 
                                        le.acc_type, 
                                        le.opening, 
                                        le.ledger_under, 
                                        ldw.date       -- added date here
                                    ORDER BY 
                                        le.ledger_name, 
                                        ldw.date;
                                    ";
                                    break;

            default:
                echo json_encode(["success" => false, "message" => "Invalid type"]);
                exit;
        }

        // Run Prepared Statement
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($bindTypes, ...$bindValues);
        $stmt->execute();
        $result = $stmt->get_result();

        // Output result
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
            echo json_encode(["success" => true, "data" => $data]);
        } else {
            echo json_encode(["success" => false, "message" => "No records found"]);
        }

        $stmt->close();

    } catch (ExpiredException $e) {
        echo json_encode(["success" => false, "message" => "Token expired"]);
    } catch (Exception $e) {
        echo json_encode(["success" => false, "message" => "Error: " . $e->getMessage()]);
    }

} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

$conn->close();
?>
