<?php
// Enable error logging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

error_log($_SERVER['REQUEST_METHOD']); // Log method to server logs

// Allow CORS
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');

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

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

$secret_key = "1ED495A77B65435D317B3E6582E4C";

// ✅ Fallback for apache_request_headers
if (!function_exists('apache_request_headers')) {
    function apache_request_headers() {
        $headers = [];
        foreach ($_SERVER as $key => $value) {
            if (substr($key, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

// ✅ Function to read Bearer token safely
function getBearerToken() {
    $headers = apache_request_headers();
    if (!isset($headers['Authorization'])) {
        echo json_encode(["success" => false, "message" => "Authorization header missing"]);
        exit;
    }
    if (preg_match('/Bearer\s(\S+)/', $headers['Authorization'], $matches)) {
        return $matches[1];
    }
    echo json_encode(["success" => false, "message" => "Invalid Authorization header format"]);
    exit;
}

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

// ✅ POST: Insert Loan Type
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $jwt = getBearerToken();

    try {
        $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
        $company_id = $decoded->data->companyId;
        $uid = $decoded->data->uid;
        $action = isset($_POST['action']) ? $_POST['action'] : '';

        if ($action === 'add') {
        if (!empty($_POST['loanType']) && !empty($_POST['dueCount'])) {
            $loanType = $_POST['loanType'];
            $dueCount = $_POST['dueCount'];

            // Check if loan type exists
            $checkQuery = "SELECT COUNT(*) as count FROM loan_type WHERE loan_type = ? AND com_id = ?";
            $checkStmt = $conn->prepare($checkQuery);
            $checkStmt->bind_param("si", $loanType, $company_id);
            $checkStmt->execute();
            $checkResult = $checkStmt->get_result();
            $checkRow = $checkResult->fetch_assoc();
            $checkStmt->close();

            if ($checkRow['count'] > 0) {
                echo json_encode(["success" => false, "message" => "Loan Type already exists!"]);
                exit;
            }

            // Insert loan type
            $stmt = $conn->prepare("INSERT INTO loan_type (loan_type, due_count, com_id) VALUES (?, ?, ?)");
            if ($stmt) {
                $stmt->bind_param("ssi", $loanType, $dueCount, $company_id);
                if ($stmt->execute()) {
                    echo json_encode(["success" => true, "message" => "Loan type inserted successfully"]);
                } else {
                    echo json_encode(["success" => false, "message" => "Failed to insert loan type: " . $stmt->error]);
                }
                $stmt->close();
            } else {
                echo json_encode(["success" => false, "message" => "Failed to prepare insert statement"]);
            }
        } else {
            echo json_encode(["success" => false, "message" => "Required fields are missing"]);
        }
    }
        elseif ($action === 'edit') {
            if (!empty($_POST['id']) && !empty($_POST['loanType'])) {
                $id = intval($_POST['id']);
                $loanType = $_POST['loanType'];
                $dueCount = $_POST['dueCount'];

                $stmt = $conn->prepare("UPDATE loan_type SET due_count = ? WHERE id = ? AND com_id = ? AND loan_type = ?");
                $stmt->bind_param("siis", $dueCount, $id, $company_id, $loanType);

                if ($stmt->execute()) {
                    if ($stmt->affected_rows > 0) {
                        echo json_encode(["success" => true, "message" => "Loan Type updated successfully"]);
                    } else {
                        echo json_encode(["success" => false, "message" => "No matching record found or no changes made"]);
                    }
                } else {
                    echo json_encode(["success" => false, "message" => "Failed to update area: " . $stmt->error]);
                }
                $stmt->close();
            } else {
                echo json_encode(["success" => false, "message" => "id and main_area are required"]);
            }
        }
    } catch (ExpiredException $e) {
        echo json_encode(["success" => false, "message" => "Token has expired"]);
    } catch (Exception $e) {
        echo json_encode(["success" => false, "message" => "Failed to decode token: " . $e->getMessage()]);
    }
}

// ✅ GET: Fetch due_count by loan_type
elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {

    if (!isset($_GET['loan_type']) || empty($_GET['loan_type'])) {
        echo json_encode(['success' => false, 'message' => 'Loan type is required']);
        exit;
    }

    $jwt = getBearerToken();

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

        $loan_type = $_GET['loan_type'];

        // Fetch due_count
        $stmt = $conn->prepare("SELECT due_count FROM loan_type WHERE loan_type = ? AND com_id = ?");
        $stmt->bind_param("si", $loan_type, $company_id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            echo json_encode([
                'success' => true,
                'due_count' => $row['due_count']
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Loan type not found']);
        }

        $stmt->close();
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $jwt = getBearerToken();
    $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
        $company_id = $decoded->data->companyId;
        $uid = $decoded->data->uid;
    if (!empty($_GET['id'])) {
        $id = intval($_GET['id']);

        $stmt = $conn->prepare("DELETE FROM loan_type WHERE id = ? AND com_id = ?");
        $stmt->bind_param("ii", $id, $company_id);
error_log("DELETE request: id=$id, com_id=$company_id");

        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                echo json_encode(["success" => true, "message" => "Area deleted successfully"]);
            } else {
                echo json_encode(["success" => false, "message" => "No matching record found"]);
            }
        } else {
            echo json_encode(["success" => false, "message" => "Failed to delete area: " . $stmt->error]);
        }
        $stmt->close();
    } else {
        echo json_encode(["success" => false, "message" => "id is required"]);
    }
}


// ✅ OPTIONS Request (CORS Preflight)
elseif ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

// Close DB only once
if ($conn) {
    $conn->close();
}
