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

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

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

$secret_key = "1ED495A77B65435D317B3E6582E4C";

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

// Extract JWT from Authorization header
function extractJWT() {
    $headers = null;
    if (function_exists('apache_request_headers')) {
        $headers = apache_request_headers();
    } else {
        // Fallback for servers that don't support apache_request_headers
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
    }
    
    if (isset($headers['Authorization'])) {
        $authHeader = $headers['Authorization'];
        if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
            return $matches[1];
        }
    }
    return null;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $jwt = extractJWT();
    
    if (!$jwt) {
        http_response_code(401);
        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' parameter
        if (!isset($_GET['type'])) {
            http_response_code(400);
            echo json_encode(["success" => false, "message" => "Type parameter is required"]);
            exit;
        }

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

        switch ($type) {
            case 'day_book_data':
                // Get optional date filters
                $from_date = isset($_GET['from_date']) ? trim($_GET['from_date']) : null;
                $to_date = isset($_GET['to_date']) ? trim($_GET['to_date']) : null;
                $ledger_name = isset($_GET['ledger_name']) ? trim($_GET['ledger_name']) : null;
                $particulars = isset($_GET['particulars']) ? trim($_GET['particulars']) : null;

                // Build SQL query with optional filters
                $sql = "SELECT 
                            id,
                            com_id,
                            uid,
                            date,
                            ledger,
                            particulars,
                            voucher_type,
                            voucher_number,
                            credit,
                            debit,
                            createdOn
                        FROM ledger_day_wise
                        WHERE com_id = ?";
                
                // Add date filters if provided
                if ($from_date !== null && $from_date !== '') {
                    $sql .= " AND date >= ?";
                    $bindTypes .= "s";
                    $bindValues[] = $from_date;
                }
                
                if ($to_date !== null && $to_date !== '') {
                    $sql .= " AND date <= ?";
                    $bindTypes .= "s";
                    $bindValues[] = $to_date;
                }
                
                // Add ledger filter if provided
                if ($ledger_name !== null && $ledger_name !== '') {
                    $sql .= " AND ledger = ?";
                    $bindTypes .= "s";
                    $bindValues[] = $ledger_name;
                }
                
                // Add particulars filter if provided (using LIKE for partial matching)
                if ($particulars !== null && $particulars !== '') {
                    $sql .= " AND particulars LIKE ?";
                    $bindTypes .= "s";
                    $bindValues[] = '%' . $particulars . '%';
                }
                
                // Order by date and id for consistent ordering
                $sql .= " ORDER BY date ASC, id ASC";
                break;

            default:
                http_response_code(400);
                echo json_encode(["success" => false, "message" => "Invalid type provided. Supported types: day_book_data"]);
                exit;
        }

        // Execute query
        if (!empty($sql)) {
            $stmt = $conn->prepare($sql);
            
            if (!$stmt) {
                http_response_code(500);
                echo json_encode(["success" => false, "message" => "Database error: " . $conn->error]);
                exit;
            }
            
            $stmt->bind_param($bindTypes, ...$bindValues);
            $stmt->execute();
            $result = $stmt->get_result();

            if ($result->num_rows > 0) {
                $data = [];
                while ($row = $result->fetch_assoc()) {
                    // Ensure numeric values are properly formatted
                    $row['credit'] = floatval($row['credit'] ?? 0);
                    $row['debit'] = floatval($row['debit'] ?? 0);
                    $data[] = $row;
                }
                
                echo json_encode([
                    "success" => true, 
                    "data" => $data,
                    "count" => count($data)
                ]);
            } else {
                echo json_encode([
                    "success" => true, 
                    "data" => [],
                    "count" => 0,
                    "message" => "No records found for the given criteria"
                ]);
            }
            
            $stmt->close();
        }

    } catch (ExpiredException $e) {
        http_response_code(401);
        echo json_encode(["success" => false, "message" => "Token expired"]);
        exit;
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(["success" => false, "message" => "Error: " . $e->getMessage()]);
        exit;
    }
} else {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed. Only GET requests are supported.']);
}

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

