<?php
session_start();

include('con.php');
include('header.php');

if (!isset($_SESSION['phone'])) {
    header("Location: login.php");
    exit;
}

$username   = $_SESSION['phone'];
$errorMsg   = null;
$successMsg = null;

/* ================= USER DATA ================= */

$udata = mysqli_fetch_assoc(
    mysqli_query($ahk_conn,
        "SELECT * FROM users WHERE phone='$username'"
    )
);

$wallet    = floatval($udata['balance']);
$user_id   = $udata['id'];
$usertype  = $udata['type'];
$name_user = $udata['name'];

/* ================= SERVICE RATE ================= */

$priceRow = mysqli_fetch_assoc(
    mysqli_query($ahk_conn,
        "SELECT rate FROM price WHERE service='aadhar'"
    )
);

$fee = $priceRow ? floatval($priceRow['rate']) : 0;

/* ================= CHECK STATUS API ================= */

if (isset($_GET['check_status'])) {

    $oid = mysqli_real_escape_string(
        $ahk_conn,
        $_GET['check_status']
    );

    $status_api =
        "https://www.maxxapi.site/reg_status.php?order_id=".$oid;

    $ch = curl_init();

    curl_setopt_array($ch, [
        CURLOPT_URL => $status_api,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
    ]);

    $status_response = curl_exec($ch);

    if (curl_errno($ch)) {

        $errorMsg = curl_error($ch);

    } else {

        $statusData = json_decode($status_response, true);

        /*
        SAMPLE RESPONSE

        {
          "status":"200",
          "order_id":"AAD1779808538537",
          "order_status":"Completed"
        }
        */

        if ($statusData && isset($statusData['status'])) {

            $api_status = strtolower(
                trim($statusData['order_status'] ?? 'pending')
            );

            // CONVERT TO DB STATUS

            if ($api_status == "pending") {

                $db_status = 0;

            } elseif (
                $api_status == "processing" ||
                $api_status == "in process"
            ) {

                $db_status = 1;

            } elseif (
                $api_status == "completed" ||
                $api_status == "success"
            ) {

                $db_status = 2;

            } else {

                $db_status = 0;
            }

            // UPDATE DATABASE

            mysqli_query($ahk_conn, "
                UPDATE aadhaar_history
                SET status='$db_status'
                WHERE order_id='$oid'
            ");

            $successMsg =
                "Status Updated : ".$statusData['order_status'];

        } else {

            $errorMsg = "Invalid status API response.";
        }
    }

    curl_close($ch);
}

/* ================= SUBMIT FORM ================= */

if (isset($_POST['submit_aadhar'])) {

    $aadhar_no   = preg_replace(
        '/\s+/',
        '',
        trim($_POST['aadhar_no'])
    );

    $person_name = trim($_POST['person_name']);

    $state = trim($_POST['state']);

    $date = date("Y-m-d H:i:s");

    if ($wallet < $fee) {

        $errorMsg = "Insufficient wallet balance.";

    } else {

        /* ================= API CALL ================= */

        $api_key = "demo";

        $api_url =
            "https://www.maxxapi.site/reg?api_key=".$api_key.
            "&aadhar_no=".urlencode($aadhar_no).
            "&name=".urlencode($person_name).
            "&state=".urlencode($state);

        $ch = curl_init();

        curl_setopt_array($ch, [
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_FOLLOWLOCATION => true
        ]);

        $response = curl_exec($ch);

        if (curl_errno($ch)) {

            $errorMsg = curl_error($ch);

        } else {

            $apiData = json_decode($response, true);

            /*
            SAMPLE RESPONSE

            {
              "status":"200",
              "message":"Aadhaar Farmer Mismatch request submitted successfully",
              "order_id":"AAD1779808538537",
              "aadhar_no":"968202993940",
              "name":"love",
              "state":"up",
              "service_fee":50,
              "balance_left":66,
              "order_status":"Pending"
            }
            */

            if (!$apiData || !isset($apiData['status'])) {

                $errorMsg = "Invalid API response.";

            } elseif ($apiData['status'] != "200") {

                $errorMsg =
                    $apiData['message'] ?? "Request failed.";

            } else {

                /* ================= API VALUES ================= */

                $api_order_id = mysqli_real_escape_string(
                    $ahk_conn,
                    $apiData['order_id'] ?? ''
                );

                $api_status = strtolower(
                    trim($apiData['order_status'] ?? 'pending')
                );

                // STATUS CONVERT

                if ($api_status == "pending") {

                    $db_status = 0;

                } elseif (
                    $api_status == "processing" ||
                    $api_status == "in process"
                ) {

                    $db_status = 1;

                } elseif (
                    $api_status == "completed" ||
                    $api_status == "success"
                ) {

                    $db_status = 2;

                } else {

                    $db_status = 0;
                }

                /* ================= UPDATE WALLET ================= */

                $new_balance = $wallet - $fee;

                mysqli_query(
                    $ahk_conn,
                    "UPDATE users
                     SET balance='$new_balance'
                     WHERE phone='$username'"
                );

                /* ================= SAVE MAIN TABLE ================= */

                mysqli_query($ahk_conn, "
                    INSERT INTO aadhar_updates
                    (
                        aadhar_no,
                        name,
                        state,
                        date,
                        username
                    )
                    VALUES
                    (
                        '$aadhar_no',
                        '$person_name',
                        '$state',
                        '$date',
                        '$username'
                    )
                ");

                /* ================= SAVE HISTORY ================= */

                mysqli_query($ahk_conn, "
                    INSERT INTO aadhaar_history
                    (
                        order_id,
                        aadhar_no,
                        name,
                        state,
                        date,
                        username,
                        status
                    )
                    VALUES
                    (
                        '$api_order_id',
                        '$aadhar_no',
                        '$person_name',
                        '$state',
                        '$date',
                        '$username',
                        '$db_status'
                    )
                ");

                /* ================= WALLET HISTORY ================= */

                mysqli_query($ahk_conn, "
                    INSERT INTO wallethistory
                    (
                        userid,
                        amount,
                        balance,
                        purpose,
                        status,
                        type
                    )
                    VALUES
                    (
                        '$username',
                        '$fee',
                        '$new_balance',
                        'Farmer Mismatch Services',
                        '1',
                        'Debit'
                    )
                ");

                $successMsg =
                    $apiData['message'];
            }
        }

        curl_close($ch);
    }
}

/* ================= HISTORY ================= */

$historyQuery = mysqli_query(
    $ahk_conn,
    "SELECT * FROM aadhaar_history
     WHERE username='$username'
     ORDER BY id DESC"
);

?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<title>Farmer Registry Mismatch</title>

<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"
rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>

.card-custom{
    border-radius:12px;
    border:none;
    box-shadow:0 8px 20px rgba(0,0,0,0.1);
}

.status-badge{
    padding:6px 12px;
    border-radius:30px;
    font-size:12px;
    font-weight:bold;
}

.bg-pending{
    background:#0d6efd;
    color:#fff;
}

.bg-processing{
    background:#ffc107;
    color:#000;
}

.bg-completed{
    background:#28a745;
    color:#fff;
}

.table-hover tbody tr:hover{
    background:#f0f7ff;
}

</style>

</head>

<body class="bg-light">

<div class="container-fluid py-4">

<div class="row g-4">

<!-- ================= LEFT FORM ================= -->

<div class="col-lg-4">

<div class="card card-custom p-4 bg-white">

<div class="card-header bg-primary text-white text-center fw-bold">

Farmer Registry Mismatch

</div>

<div class="card-body">

<div class="alert alert-info text-center small">

Processing time: 15-20 Minutes

<br><br>

Check History for latest status.

</div>

<form method="POST">

<div class="mb-3">

<label class="form-label fw-bold">

Aadhaar Number

</label>

<input
type="text"
name="aadhar_no"
required
class="form-control text-center fw-bold"
placeholder="Enter Aadhaar Number"
oninput="this.value=this.value.replace(/\s/g,'')">

</div>

<div class="mb-3">

<label class="form-label fw-bold">

Name

</label>

<input
type="text"
name="person_name"
required
class="form-control"
placeholder="Enter Name">

</div>

<div class="mb-3">

<label class="form-label fw-bold">

State

</label>

<select
name="state"
required
class="form-select">

<option value="">Select State</option>

<option value="up">Uttar Pradesh</option>
<option value="bihar">Bihar</option>
<option value="punjab">Punjab</option>
<option value="haryana">Haryana</option>
<option value="rajasthan">Rajasthan</option>
<option value="mp">Madhya Pradesh</option>
<option value="maharashtra">Maharashtra</option>
<option value="gujarat">Gujarat</option>
<option value="jharkhand">Jharkhand</option>
<option value="cg">Chhattisgarh</option>

</select>

</div>

<button
type="submit"
name="submit_aadhar"
class="btn btn-success w-100">

Submit (₹<?= number_format($fee,2); ?>)

</button>

</form>

</div>
</div>
</div>

<!-- ================= HISTORY ================= -->

<div class="col-lg-8">

<div class="card card-custom shadow">

<div class="card-header bg-primary text-white text-center">

<h4 class="mb-0">

Farmer Registry Update History

</h4>

</div>

<div class="card-body table-responsive p-4">

<table class="table table-bordered table-striped table-hover align-middle text-center">

<thead class="table-dark">

<tr>

<th>ID</th>
<th>Aadhaar</th>
<th>Name</th>
<th>State</th>
<th>Order ID</th>
<th>Date</th>
<th>Status</th>
<th>Action</th>

</tr>

</thead>

<tbody>

<?php if(mysqli_num_rows($historyQuery) > 0): ?>

<?php while($row = mysqli_fetch_assoc($historyQuery)): ?>

<tr>

<td><?= $row['id']; ?></td>

<td><?= htmlspecialchars($row['aadhar_no']); ?></td>

<td class="fw-semibold text-primary">
<?= htmlspecialchars($row['name']); ?>
</td>

<td><?= htmlspecialchars($row['state']); ?></td>

<td><?= htmlspecialchars($row['order_id']); ?></td>

<td><?= htmlspecialchars($row['date']); ?></td>

<td>

<?php

$status = intval($row['status']);

if ($status == 0) {

    echo '<span class="status-badge bg-pending">
    Pending
    </span>';

} elseif ($status == 1) {

    echo '<span class="status-badge bg-processing">
    Processing
    </span>';

} elseif ($status == 2) {

    echo '<span class="status-badge bg-completed">
    Completed
    </span>';

}

?>

</td>

<td>

<a
href="?check_status=<?= urlencode($row['order_id']); ?>"
class="btn btn-sm btn-primary">

Check Status

</a>

</td>

</tr>

<?php endwhile; ?>

<?php else: ?>

<tr>

<td colspan="8" class="text-muted py-3">

No records found

</td>

</tr>

<?php endif; ?>

</tbody>

</table>

</div>
</div>
</div>

</div>
</div>

<?php if ($errorMsg): ?>

<script>

Swal.fire({
    icon:'error',
    title:'Error',
    text:<?= json_encode($errorMsg); ?>
});

</script>

<?php endif; ?>

<?php if ($successMsg): ?>

<script>

Swal.fire({
    icon:'success',
    title:'Success',
    text:<?= json_encode($successMsg); ?>
});

</script>

<?php endif; ?>

<?php include('footer.php'); ?>

</body>
</html>