<?php
// ==========================
// Error reporting and logging
// ==========================
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_error.log');
error_reporting(E_ALL);

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

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

// ==========================
// JWT Configuration
// ==========================
$secret_key = "1ED495A77B65435D317B3E6582E4C";
$issuer = "http://kaninfotech.in";
$audience = "http://xesstechlink.com";

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

// ==========================
// Process Only POST Requests
// ==========================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Safe 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_') {
                    $header = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))));
                    $headers[$header] = $value;
                }
            }
            return $headers;
        }
    }

    $headers = apache_request_headers();

    // ==========================
    // Validate Authorization Header
    // ==========================
    if (!isset($headers['Authorization'])) {
        echo json_encode(["success" => false, "message" => "Authorization header missing"]);
        exit;
    }

    $authHeader = $headers['Authorization'];
    list($jwt) = sscanf($authHeader, 'Bearer %s');

    if (empty($jwt)) {
        echo json_encode(["success" => false, "message" => "Invalid JWT format"]);
        exit;
    }

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

        if (!$company_id || !$uid) {
            echo json_encode(["success" => false, "message" => "Invalid JWT payload"]);
            exit;
        }

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

    // ==========================
    // Validate Required Fields
    // ==========================
    if (empty($_POST['loan_id']) || empty($_POST['receipt_no'])) {
        echo json_encode(["success" => false, "message" => "Customer name and mobile are required"]);
        exit;
    }

    // ==========================
    // Collect POST Data
    // ==========================
    $loan_id = $_POST['loan_id'];
    $receipt_no = $_POST['receipt_no'];
    $receiptDate      = $_POST['receipt_date'];
    $customer_id   = $_POST['cust_id'];
    $customerName   = $_POST['cus_name'];
    $customerMobile  = $_POST['cus_mobile'] ?? '';  // secondary mobile
    $numberOfDues   = $_POST['no_of_dues'] ?? '';
    $dueAmount  = $_POST['due_amt'] ?? '';
    $paidAmount = $_POST['paid_amt'] ?? '';
    $paidDues      = $_POST['paid_dues'] ?? '';
    $balanceDues  = $_POST['balance_dues'] ?? '';
    $pendingDues   = $_POST['pending_dues'] ?? '';
    $nextDate     = $_POST['next_date'] ?? null;
    $remark    = $_POST['remark'] ?? '';
    $agent   = $_POST['agent'] ?? '';
    $ledgerName = $_POST['ledgerName'] ?? '';
    $accountClose = $_POST['account_close'] ?? '';
    $principal_per_due = $_POST['principal_per_due'] ?? '';
    $interest_per_due = $_POST['interest_per_due'] ?? '';
    
    
    // ==========================
    // Insert into loan_entry with customer_id
    // ==========================
    $insertLoan = "INSERT INTO loan_receipt (
        loan_id, com_id, rec_no, rec_date, cust_id, cust_name, cust_mobile, num_dues, due_amnt, paid_amnt, paid_dues, balance_dues, pending_dues, next_date, remark, agent
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($insertLoan);
    $stmt->bind_param(
        "sississiddiiisss",
        $loan_id, $company_id, $receipt_no, $receiptDate, $customer_id, $customerName, $customerMobile, $numberOfDues, $dueAmount, $paidAmount, $paidDues, 
        $balanceDues, $pendingDues, $nextDate, $remark, $agent
    );

    if (!$stmt->execute()) {
        echo json_encode(["success" => false, "message" => "Loan insert failed: " . $stmt->error]);
        exit;
    }
    $stmt->close();

    // ==========================
    // Insert into ledger_day_wise
    // ==========================
    $particulars = $loan_id . '-' . $customerName;
    $voucher_type = 'Principal';
    $voucher_number = '';
    $zero = 0.00;

    $ledgerstmt = $conn->prepare("INSERT INTO ledger_day_wise 
        (com_id, uid, date, ledger, particulars, voucher_type, voucher_number, credit, debit) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

    $ledgerstmt->bind_param(
        "sssssssdd",
        $company_id, $uid, $receiptDate, $ledgerName, $particulars,
        $voucher_type, $receipt_no, $zero, $principal_per_due
    );

    if (!$ledgerstmt->execute()) {
        echo json_encode(["success" => false, "message" => "Ledger insert failed: " . $ledgerstmt->error]);
        exit;
    }
    $ledgerstmt->close();
    
    // ==========================
        // Insert Interest (Principal Per Due) Entry if Interest Exists
        // ==========================
        if (!empty($interest_per_due) && floatval($interest_per_due) > 0) {
        
            $interestVoucherType = 'Interest';
            $creditAmount = 0.00; // Use principal value here
            $debitAmount = floatval($interest_per_due);
        
            $interestStmt = $conn->prepare("INSERT INTO ledger_day_wise 
                (com_id, uid, date, ledger, particulars, voucher_type, voucher_number, credit, debit)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
            $interestStmt->bind_param(
                "sssssssdd",
                $company_id,
                $uid,
                $receiptDate,
                $ledgerName,
                $particulars,
                $interestVoucherType,
                $receipt_no,
                $creditAmount,
                $debitAmount
            );
        
            if (!$interestStmt->execute()) {
                echo json_encode(["success" => false, "message" => "Interest Ledger insert failed: " . $interestStmt->error]);
                exit;
            }
        
            $interestStmt->close();
        }


    // ==========================
    // Close Account (Update Loan Status)
    // ==========================
    if (!empty($accountClose) && $accountClose === "Closed") {
    
    $updateStatusQuery = "UPDATE loan_entry SET status = 'Closed' WHERE loan_id = ? AND com_id = ?";
    $closeStmt = $conn->prepare($updateStatusQuery);
    $closeStmt->bind_param("si", $loan_id, $company_id);

    if (!$closeStmt->execute()) {
        echo json_encode(["success" => false, "message" => "Failed to close account: " . $closeStmt->error]);
        exit;
    }

    $closeStmt->close();
   }



    // ==========================
    // Success Response
    // ==========================
    echo json_encode([
        "success" => true,
        "message" => "Loan inserted successfully",
        "loan_id" => $loan_id,
        "customer_id" => $customer_id
    ]);
}

else if ($_SERVER['REQUEST_METHOD'] === 'PUT') {

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

    $headers = apache_request_headers();

    // ------ Authorization header check ------
    if (!isset($headers['Authorization'])) {
        echo json_encode(["success" => false, "message" => "Authorization header missing"]);
        exit;
    }

    list($jwt) = sscanf($headers['Authorization'], 'Bearer %s');
    if (empty($jwt)) {
        echo json_encode(["success" => false, "message" => "Invalid JWT format"]);
        exit;
    }

    // ------ Decode JWT ------
    try {
        $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
        $company_id = $decoded->data->companyId ?? null;
        $uid = $decoded->data->uid ?? null;
    } catch (Exception $e) {
        echo json_encode(["success" => false, "message" => "JWT Error: " . $e->getMessage()]);
        exit;
    }

    // ------ Read PUT JSON body ------
    $input = json_decode(file_get_contents("php://input"), true);

    if (!$input) {
        echo json_encode(["success" => false, "message" => "Invalid JSON"]);
        exit;
    }

    // ------ Required fields ------
    if (empty($input['loan_id']) || empty($input['receipt_no'])) {
        echo json_encode(["success" => false, "message" => "Loan ID and Receipt No required"]);
        exit;
    }

    // ------ Assign Variables ------
    $loan_id        = $input['loan_id'];
    $receipt_no     = $input['receipt_no'];
    $receiptDate    = $input['receipt_date'];
    $customer_id    = $input['cust_id'];
    $customerName   = $input['cus_name'];
    $customerMobile = $input['cus_mobile'] ?? '';
    $numberOfDues   = $input['no_of_dues'] ?? 0;
    $dueAmount      = $input['due_amt'] ?? 0;
    $paidAmount     = $input['paid_amt'] ?? 0;
    $paidDues       = $input['paid_dues'] ?? 0;
    $balanceDues    = $input['balance_dues'] ?? 0;
    $pendingDues    = $input['pending_dues'] ?? 0;
    $nextDate       = $input['next_date'] ?? null;
    $remark         = $input['remark'] ?? '';
    $agent          = $input['agent'] ?? '';
    $ledgerName     = $input['ledgerName'] ?? '';
    $accountClose   = $input['account_close'] ?? '';
    $principal_per_due = $input['principal_per_due'] ?? 0;
    $interest_per_due  = $input['interest_per_due'] ?? 0;

    // ====================================================
    // 1️⃣ UPDATE loan_receipt TABLE
    // ====================================================
    $updateLoan = "UPDATE loan_receipt SET
        rec_date = ?, cust_id = ?, cust_name = ?, cust_mobile = ?, num_dues = ?, 
        due_amnt = ?, paid_amnt = ?, paid_dues = ?, balance_dues = ?, pending_dues = ?, 
        next_date = ?, remark = ?, agent = ?
        WHERE loan_id = ? AND rec_no = ? AND com_id = ?";

    $stmt = $conn->prepare($updateLoan);
    $stmt->bind_param(
        "sissiddiiisssssi",
        $receiptDate, $customer_id, $customerName, $customerMobile, $numberOfDues,
        $dueAmount, $paidAmount, $paidDues, $balanceDues, $pendingDues,
        $nextDate, $remark, $agent,
        $loan_id, $receipt_no, $company_id
    );

    if (!$stmt->execute()) {
        echo json_encode(["success" => false, "message" => "Loan update failed: " . $stmt->error]);
        exit;
    }
    $stmt->close();


    // ====================================================
    // 2️⃣ DELETE OLD ledger_day_wise ENTRIES FOR THIS RECEIPT
    // ====================================================
    $deleteLedger = $conn->prepare("
        DELETE FROM ledger_day_wise 
        WHERE voucher_number = ? AND com_id = ?");
    $deleteLedger->bind_param("si", $receipt_no, $company_id);
    $deleteLedger->execute();
    $deleteLedger->close();


    // ====================================================
    // 3️⃣ INSERT NEW ledger_day_wise (PRINCIPAL)
    // ====================================================
    $particulars = $loan_id . '-' . $customerName;

    $insertPrincipal = $conn->prepare("
        INSERT INTO ledger_day_wise 
        (com_id, uid, date, ledger, particulars, voucher_type, voucher_number, credit, debit)
        VALUES (?, ?, ?, ?, ?, 'Principal', ?, 0, ?)");

    $insertPrincipal->bind_param(
        "sissssd",
        $company_id, $uid, $receiptDate, $ledgerName, $particulars, $receipt_no, $principal_per_due
    );

    if (!$insertPrincipal->execute()) {
        echo json_encode(["success" => false, "message" => "Ledger principal insert failed"]);
        exit;
    }
    $insertPrincipal->close();


    // ====================================================
    // 4️⃣ INSERT NEW ledger_day_wise (INTEREST IF > 0)
    // ====================================================
    if (floatval($interest_per_due) > 0) {

        $insertInterest = $conn->prepare("
            INSERT INTO ledger_day_wise 
            (com_id, uid, date, ledger, particulars, voucher_type, voucher_number, credit, debit)
            VALUES (?, ?, ?, ?, ?, 'Interest', ?, 0, ?)");

        $insertInterest->bind_param(
            "sissssd",
            $company_id, $uid, $receiptDate, $ledgerName, $particulars, $receipt_no, $interest_per_due
        );

        if (!$insertInterest->execute()) {
            echo json_encode(["success" => false, "message" => "Ledger interest insert failed"]);
            exit;
        }

        $insertInterest->close();
    }


    // ====================================================
    // 5️⃣ ACCOUNT CLOSE
    // ====================================================
    if (!empty($accountClose) && $accountClose === "Closed") {

        $close = $conn->prepare("UPDATE loan_entry SET status='Closed' 
                                 WHERE loan_id=? AND com_id=?");
        $close->bind_param("si", $loan_id, $company_id);
        $close->execute();
        $close->close();
    }


    // ====================================================
    // SUCCESS RESPONSE
    // ====================================================
    echo json_encode([
        "success" => true,
        "message" => "Loan updated successfully",
        "loan_id" => $loan_id,
        "receipt_no" => $receipt_no
    ]);
}


// ==========================
// DELETE LOAN ENTRY
// ==========================
else if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {

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

    $headers = apache_request_headers();

    if (!isset($headers['Authorization'])) {
        echo json_encode(["success" => false, "message" => "Authorization header missing"]);
        exit;
    }

    $authHeader = $headers['Authorization'];
    list($jwt) = sscanf($authHeader, 'Bearer %s');

    try {
        $decoded = JWT::decode($jwt, new Key($secret_key, 'HS256'));
        $company_id = $decoded->data->companyId ?? null;
    } catch (Exception $e) {
        echo json_encode(["success" => false, "message" => "JWT Error: " . $e->getMessage()]);
        exit;
    }

    $input = json_decode(file_get_contents("php://input"), true);

    if (empty($input['loan_id'])) {
        echo json_encode(["success" => false, "message" => "loan_id is required"]);
        exit;
    }

    $loan_id = $input['loan_id'];
    $receipt_no = $input['receipt_no'];

    $sql = "DELETE FROM loan_receipt WHERE loan_id = ? AND rec_no = ? AND com_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssi", $loan_id, $receipt_no, $company_id);

    if ($stmt->execute()) {
        echo json_encode(["success" => true, "message" => "Loan deleted successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => "Unable to delete loan"]);
    }
    exit;
}
else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

$conn->close();
?>
