<?php
include '../../config.php';
date_default_timezone_set('Africa/Dar_es_Salaam');

// Read and decode webhook JSON payload
$body = file_get_contents("php://input");
$data = json_decode($body, true);
error_log("Selcom webhook payload: " . print_r($data, true));

// Validate required webhook fields
if (!isset(
    $data['transid'],
    $data['order_id'],
    $data['reference'],
    $data['result'],
    $data['resultcode'],
    $data['payment_status']
)) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required parameters']);
    exit;
}

$transId       = $data['transid'];
$orderId       = $data['order_id'];
$reference     = $data['reference'];
$result        = $data['result'];
$resultcode    = $data['resultcode'];
$paymentStatus = $data['payment_status'];
$tid           = isset($_GET['tid']) ? $_GET['tid'] : null;
$now           = date('Y-m-d H:i:s');

// Log transaction to transactions_logs
$stmt = $conn->prepare(
    "INSERT INTO transactions_logs (transid, order_id, reference, result, resultcode, payment_status, tid, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param("ssssssss", $transId, $orderId, $reference, $result, $resultcode, $paymentStatus, $tid, $now);
$stmt->execute();
$stmt->close();

// Only process completed payments
if ($paymentStatus === 'COMPLETED') {
    // Get pending transaction
    $q = $conn->prepare("SELECT id, loan_id, branch_id, amount, user_id FROM pending_transactions WHERE tid = ?");
    $q->bind_param("s", $tid);
    $q->execute();
    $pending = $q->get_result()->fetch_assoc();
    $q->close();

    if (!$pending) {
        error_log("No pending transaction found for tid: $tid");
        echo json_encode(['status' => 'error', 'message' => 'Pending transaction not found']);
        exit;
    }

    $loan_id   = $pending['loan_id'];
    $branch_id = $pending['branch_id'];
    $amount    = floatval($pending['amount']);
    $user_id   = $pending['user_id'];
    $payment_method = 'Selcom';

    // Insert into loans_collection
    $stmt = $conn->prepare("INSERT INTO loans_collection (customer_id, loan_id, branch_id, amount_paid, payment_method, tid, payment_date) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("iiidsss", $user_id, $loan_id, $branch_id, $amount, $payment_method, $tid, $now);
    if (!$stmt->execute()) {
        error_log("Failed to insert into loans_collection: " . $stmt->error);
        echo json_encode(['status' => 'error', 'message' => 'Failed to record collection']);
        exit;
    }
    $stmt->close();

    // Update loan schedule
    $stmt = $conn->prepare("SELECT id, scheduled_amount, paid_amount FROM loans_schedule WHERE loan_id = ? AND status != 'Full Paid' ORDER BY schedule_date ASC");
    $stmt->bind_param("i", $loan_id);
    $stmt->execute();
    $result = $stmt->get_result();

    while (($row = $result->fetch_assoc()) && $amount > 0) {
        $schedule_id     = $row['id'];
        $scheduled       = floatval($row['scheduled_amount']);
        $already_paid    = floatval($row['paid_amount']);
        $remaining       = $scheduled - $already_paid;

        if ($amount >= $remaining) {
            $new_paid = $scheduled;
            $new_status = 'Full Paid';
            $amount -= $remaining;
        } else {
            $new_paid = $already_paid + $amount;
            $new_status = ($new_paid == $scheduled) ? 'Full Paid' : 'Partial Paid';
            $amount = 0;
        }

        $stmt_upd = $conn->prepare("UPDATE loans_schedule SET paid_amount = ?, status = ? WHERE id = ?");
        $stmt_upd->bind_param("dsi", $new_paid, $new_status, $schedule_id);
        $stmt_upd->execute();
        $stmt_upd->close();
    }
    $stmt->close();

    // Check if loan is now fully paid
    $stmt = $conn->prepare("SELECT COUNT(*) FROM loans_schedule WHERE loan_id = ? AND status != 'Full Paid'");
    $stmt->bind_param("i", $loan_id);
    $stmt->execute();
    $stmt->bind_result($pending_count);
    $stmt->fetch();
    $stmt->close();

    if ($pending_count == 0) {
        $stmt = $conn->prepare("UPDATE loans SET status = 'Paid' WHERE loan_id = ?");
        $stmt->bind_param("i", $loan_id);
        $stmt->execute();
        $stmt->close();
    }

    echo json_encode(['status' => 'success', 'message' => 'Repayment processed']);
} else {
    echo json_encode(['status' => 'info', 'message' => 'Payment not completed']);
}
