<?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";

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;
}

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

    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');

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

    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;
    }

    if (empty($_POST['cus_name']) || empty($_POST['cust_mobile'])) {
        echo json_encode(["success" => false, "message" => "Customer name and mobile are required"]);
        exit;
    }

    $cus_name      = $_POST['cus_name'];
    $cust_mobile   = $_POST['cust_mobile'];
    $cust_mobile2  = $_POST['cust_contact'] ?? '';
    $building_no   = $_POST['cust_address'] ?? '';
    $street        = $_POST['cust_address2'] ?? '';
    $area          = $_POST['area'] ?? '';
    $city          = $_POST['city'] ?? '';
    $district      = $_POST['district'] ?? '';
    $pincode       = $_POST['pincode'] ?? '';
    $image         = $_POST['image'] ?? null;
    $aadhaar_no    = $_POST['aadhaar_no'] ?? '';
    $pan_no        = $_POST['pan_no'] ?? '';
    $latitude      = $_POST['latitude'] ?? 0;
    $longitude     = $_POST['longitude'] ?? 0;

    $loan_type     = $_POST['loan_type'] ?? '';
    $loan_amt      = floatval($_POST['loan_amt'] ?? 0);
    $dues          = intval($_POST['dues'] ?? 0);
    $interest      = floatval($_POST['interest'] ?? 0);
    $interest_amt  = floatval($_POST['interest_amt'] ?? 0);
    $total_amt     = floatval($_POST['total_amt'] ?? 0);
    $per_due_amt   = floatval($_POST['per_due_amt'] ?? 0);
    $next_due_date = $_POST['next_due_date'] ?? '';
    $last_due_date = $_POST['last_due_date'] ?? '';
    $loan_date     = $_POST['loan_date'] ?? date('Y-m-d');
    $pre_interest  = $_POST['pre_interest'] ?? '';
    $ledger        = $_POST['ledger'] ?? '';
    $due_schedule  = $_POST['due_schedule'] ?? '';

    // Check existing customer
    $customer_id = null;
    $checkCustomer = "SELECT id FROM customers WHERE (cust_mobile = ? OR aadhar_no = ?) AND com_id = ? LIMIT 1";
    $stmt = $conn->prepare($checkCustomer);
    $stmt->bind_param("ssi", $cust_mobile, $aadhaar_no, $company_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        $customer_id = $row['id'];
    } else {
        $insertCustomer = "INSERT INTO customers 
            (com_id, cust_name, cust_mobile, cust_mobile2, building_no, street, area, city, district, pincode, aadhar_no, pan_no, latitude, longitude) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt2 = $conn->prepare($insertCustomer);
        $stmt2->bind_param(
            "isssssssssssdd",
            $company_id,
            $cus_name,
            $cust_mobile,
            $cust_mobile2,
            $building_no,
            $street,
            $area,
            $city,
            $district,
            $pincode,
            $aadhaar_no,
            $pan_no,
            $latitude,
            $longitude
        );
        $stmt2->execute();
        $customer_id = $stmt2->insert_id;
        $stmt2->close();
    }
    $stmt->close();

    $year = date("Y");
    $prefix = "DL" . $year;

    $query = "SELECT loan_id FROM loan_entry WHERE com_id = ? AND loan_id LIKE ? ORDER BY loan_id DESC LIMIT 1";
    $stmt = $conn->prepare($query);
    $likePattern = $prefix . "%";
    $stmt->bind_param("is", $company_id, $likePattern);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        $lastNumber = intval(substr($row['loan_id'], -3));
        $nextNumber = str_pad($lastNumber + 1, 3, "0", STR_PAD_LEFT);
    } else {
        $nextNumber = "001";
    }
    $stmt->close();
    $loan_id = $prefix . $nextNumber;
    $status = 'Active';

    $insertLoan = "INSERT INTO loan_entry (
        loan_id, com_id, cust_id, cus_name, cust_mobile, cust_contact, cust_address, cust_address2, area,
        loan_type, loan_amt, dues, interest, interest_amt, total_amt, per_due_amt,
        next_due_date, last_due_date, aadhaar_no, loan_date, pre_interest, ledger, status
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($insertLoan);
    $stmt->bind_param(
        "siissssssssddddssssssss",
        $loan_id, $company_id, $customer_id, $cus_name, $cust_mobile, $cust_mobile2, $building_no,
        $street, $area, $loan_type, $loan_amt, $dues, $interest, $interest_amt,
        $total_amt, $per_due_amt, $next_due_date, $last_due_date, $aadhaar_no,
        $loan_date, $pre_interest, $ledger, $status
    );
    $stmt->execute();
    $stmt->close();

    // ==========================
    // Insert into ledger_day_wise (Loan Given)
    // ==========================
    $particulars = $loan_id . '-' . $cus_name;
    $voucher_type = 'Loan';
    $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, $loan_date, $ledger, $particulars,
        $voucher_type, $voucher_number, $loan_amt, $zero
    );
    $ledgerstmt->execute();
    $ledgerstmt->close();

    // ==========================
    // INSERT INTEREST IN LEDGER WHEN PRE INTEREST = YES
    // ==========================
    if (strtolower($pre_interest) == "yes" && $interest_amt > 0) {

        $interest_particulars = $loan_id . "-" . $cus_name;
        $voucher_type2 = "Pre Interest";

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

        $credit_zero = 0.00;
        $ledgerstmt2->bind_param(
            "sssssssdd",
            $company_id, $uid, $loan_date, $ledger, $interest_particulars, 
            $voucher_type2, $voucher_number, $credit_zero, $interest_amt
        );
        $ledgerstmt2->execute();
        $ledgerstmt2->close();
    }

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

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

    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');

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

    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;
    }

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

    if (!$input) {
        parse_str($raw, $input);
    }

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

    $loan_id = $input['loan_id'];

    // Collect fields
    $cus_name      = $input['cus_name'] ?? '';
    $cust_mobile   = $input['cust_mobile'] ?? '';
    $cust_mobile2  = $input['cust_contact'] ?? '';
    $building_no   = $input['cust_address'] ?? '';
    $street        = $input['cust_address2'] ?? '';
    $area          = $input['area'] ?? '';
    $city          = $input['city'] ?? '';
    $district      = $input['district'] ?? '';
    $pincode       = $input['pincode'] ?? '';
    $aadhaar_no    = $input['aadhaar_no'] ?? '';
    $pan_no        = $input['pan_no'] ?? '';
    $loan_type     = $input['loan_type'] ?? '';
    $loan_amt      = floatval($input['loan_amt'] ?? 0);
    $dues          = intval($input['dues'] ?? 0);
    $interest      = floatval($input['interest'] ?? 0);
    $interest_amt  = floatval($input['interest_amt'] ?? 0);
    $total_amt     = floatval($input['total_amt'] ?? 0);
    $per_due_amt   = floatval($input['per_due_amt'] ?? 0);
    $next_due_date = $input['next_due_date'] ?? '';
    $last_due_date = $input['last_due_date'] ?? '';
    $loan_date     = $input['loan_date'] ?? '';
    $pre_interest  = $input['pre_interest'] ?? '';
    $ledger        = $input['ledger'] ?? '';
    $status        = $input['status'] ?? 'Active';

    // ----------------------
    // Update Loan
    // ----------------------
    $updateLoan = "UPDATE loan_entry SET 
        cus_name=?, cust_mobile=?, cust_contact=?, cust_address=?, cust_address2=?, area=?, 
        loan_type=?, loan_amt=?, dues=?, interest=?, interest_amt=?, total_amt=?, per_due_amt=?,
        next_due_date=?, last_due_date=?, aadhaar_no=?, loan_date=?, pre_interest=?, ledger=?, status=?
        WHERE loan_id=? AND com_id=?";

    $stmt = $conn->prepare($updateLoan);
    $stmt->bind_param(
        "sssssssidddddssssssssi",
        $cus_name, $cust_mobile, $cust_mobile2, $building_no, $street, $area,
        $loan_type, $loan_amt, $dues, $interest, $interest_amt, $total_amt, $per_due_amt,
        $next_due_date, $last_due_date, $aadhaar_no, $loan_date, $pre_interest, $ledger, $status,
        $loan_id, $company_id
    );

    if (!$stmt->execute()) {
        echo json_encode(["success" => false, "message" => "Failed to update loan"]);
        exit;
    }
    $stmt->close();


    // ---------------------------------------
    // DELETE OLD LEDGER ENTRIES FOR THIS LOAN
    // ---------------------------------------
    $del = $conn->prepare("DELETE FROM ledger_day_wise WHERE particulars LIKE ?");
    $like = $loan_id . "%";
    $del->bind_param("s", $like);
    $del->execute();
    $del->close();

    // ---------------------------------------
    // INSERT NEW LEDGER ENTRY (LOAN GIVEN)
    // ---------------------------------------
    $particulars = $loan_id . '-' . $cus_name;
    $voucher_type = 'Loan';
    $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, $loan_date, $ledger, $particulars,
        $voucher_type, $voucher_number, $loan_amt, $zero
    );
    $ledgerstmt->execute();
    $ledgerstmt->close();


    // -----------------------------------------------
    // INSERT PRE-INTEREST ENTRY (IF APPLICABLE)
    // -----------------------------------------------
    if (strtolower($pre_interest) == "yes" && $interest_amt > 0) {

        $interest_particulars = $loan_id . "-" . $cus_name;
        $voucher_type2 = "Pre Interest";
        $credit_zero = 0.00;

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

        $ledgerstmt2->bind_param(
            "sssssssdd",
            $company_id, $uid, $loan_date, $ledger, $interest_particulars,
            $voucher_type2, $voucher_number, $credit_zero, $interest_amt
        );
        $ledgerstmt2->execute();
        $ledgerstmt2->close();
    }

    echo json_encode([
        "success" => true,
        "message" => "Loan updated successfully with ledger entries"
    ]);
}



// ==========================
// 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'];
    
     $delLedger = $conn->prepare("DELETE FROM ledger_day_wise WHERE particulars LIKE ?");
    $like = $loan_id . '%';
    $delLedger->bind_param("s", $like);
    $delLedger->execute();
    $delLedger->close();

    $sql = "DELETE FROM loan_entry WHERE loan_id = ? AND com_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("si", $loan_id, $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();
?>
