<?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'; // Load Composer dependencies

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

$secret_key = "1ED495A77B65435D317B3E6582E4C"; // Replace with your secret key

// Check 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;

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

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

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

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

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

        switch ($type) {
                   
                /*case 'profit_loss':
                    $sql = "
                                            SELECT 
    le.ledger_name,
    le.ledger_under,
    ldw.voucher_type,
    ldw.date,
    IFNULL(SUM(ldw.credit), 0) AS total_credit
FROM 
    ledger_day_wise ldw
INNER JOIN 
    ledger_entry le ON le.ledger_name = ldw.ledger
WHERE 
    ldw.com_id = ?
    AND (
            le.ledger_under = 'Expenses'
         OR ldw.voucher_type IN ('Loan Interest', 'Loan Diff')
        )
GROUP BY 
    le.ledger_name,
    le.ledger_under,
    ldw.voucher_type,
    ldw.date
ORDER BY 
    le.ledger_under,
    ldw.voucher_type,
    le.ledger_name,
    ldw.date;
                    ";
                    break;*/
                    
                    case 'profit_loss':
                    $sql = "
                                            SELECT 
    le.ledger_name AS particulars,
    le.ledger_under,
    ldw.voucher_type,
    ldw.date,
    
    CASE 
        WHEN le.ledger_under = 'Expenses' THEN IFNULL(SUM(ldw.credit), 0)
        ELSE IFNULL(SUM(ldw.debit), 0)
    END AS amount

FROM 
    ledger_day_wise ldw
INNER JOIN 
    ledger_entry le ON le.ledger_name = ldw.ledger

WHERE 
    ldw.com_id = ?
    AND (
            le.ledger_under = 'Expenses'
         OR ldw.voucher_type IN ('Interest', 'Loan Diff')
        )

GROUP BY 
    le.ledger_name,
    le.ledger_under,
    ldw.voucher_type,
    ldw.date

ORDER BY 
    le.ledger_under,
    ldw.voucher_type,
    le.ledger_name,
    ldw.date;

                    ";
                    break;
    
    
    /*SELECT 
            le.ledger_name,
            le.ledger_under,
            IFNULL(SUM(ldw.credit), 0) AS total_credit
        FROM 
            ledger_day_wise ldw
        INNER JOIN 
            ledger_entry le ON le.ledger_name = ldw.ledger
        WHERE 
            le.ledger_under = 'Expenses'
            AND ldw.com_id = ?
        GROUP BY 
            le.ledger_name, le.ledger_under
        ORDER BY 
            le.ledger_under, le.ledger_name;*/
    
    
    case 'profit_loss_income':
    $sql = "
        SELECT 
            le.ledger_name,
            le.ledger_under,
            IFNULL(SUM(ldw.credit), 0) AS total_credit
        FROM 
            ledger_day_wise ldw
        INNER JOIN 
            ledger_entry le ON le.ledger_name = ldw.ledger
        WHERE 
            ldw.voucher_type IN ('Loan Interest', 'Loan Diff')
            AND ldw.com_id = ?
        GROUP BY 
            ldw.voucher_type,
            le.ledger_name, 
            le.ledger_under
        ORDER BY 
            le.ledger_under, le.ledger_name;
    ";
    break;


    
 /*case 'profit_loss_income':
    $sql = "
        SELECT 
            le.ledger_name,
            le.ledger_under,
            IFNULL(SUM(ldw.debit), 0) AS total_credit
        FROM 
            ledger_day_wise ldw
        INNER JOIN 
            ledger_entry le ON le.ledger_name = ldw.ledger
        WHERE 
            ldw.voucher_type IN ('Loan Interest', 'Loan Diff')
            AND ldw.com_id = ?
        GROUP BY 
            le.ledger_name, le.ledger_under
        ORDER BY 
            le.ledger_under, le.ledger_name;
    ";
    break;
*/

            

            

            

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

        // Prepare and bind dynamically
        if (!empty($sql)) {
            $stmt = $conn->prepare($sql);
            $stmt->bind_param($bindTypes, ...$bindValues);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $data = [];
                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"]);
        exit;
    } catch (Exception $e) {
        echo json_encode(["success" => false, "message" => "Error: " . $e->getMessage()]);
        exit;
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

// Close the connection
$conn->close();
?>
