<?php
include('con.php');

$msg = '';

// =========================
// SMS Send Function
// =========================
function sendSMS($memberid, $membername, $username) {
    $sms_message = urlencode("Hello Dear,Member ID $memberid | Name: $membername | Successfully Proceed Please Download From Family Id History Option");
    $sms_url = "https://sms.liveone.tech/send-message?api_key=5BStKiAVs0Bb9vddDJR9u8rieXXUVU&sender=917973553513&number=91$username&message=$sms_message";

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $sms_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
}

// =================================================
// HANDLE CERTIFICATE UPLOAD (SET STATUS=2)
// =================================================
if (isset($_POST['upload_cert'])) {

    $id = intval($_POST['history_id']);
    $file = $_FILES['certificate']['name'];
    $upload_dir = "new/fmpcert/";

    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    $file_path = $upload_dir . time() . "_" . basename($file);
    $allowed_types = ['jpg', 'jpeg', 'png', 'webp', 'pdf'];
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed_types)) {
        $msg = "Only JPG, JPEG, PNG, WEBP, and PDF files are allowed.";
    } else {

        if (move_uploaded_file($_FILES['certificate']['tmp_name'], $file_path)) {

            // Update certificate and set status to completed
            mysqli_query($ahk_conn, "UPDATE mphistory SET cert='$file_path', status=2 WHERE id='$id'");

            $msg = "Certificate uploaded successfully!";

            // Fetch member details
            $row = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT dl_no, order_id, username, name FROM mphistory WHERE id='$id'"));
            $memberid = $row['dl_no'];
            $order = $row['order_id'];
            $membername = $row['name'] ?? '';
            $username = $row['username'] ?? '';

            // Send SMS
            sendSMS($memberid, $membername, $username);

        } else {
            $msg = "Error uploading file.";
        }
    }
}

// =================================================
// STATUS UPDATE
// =================================================
if (isset($_POST['update_status'])) {

    $id = intval($_POST['history_id']);
    $status = intval($_POST['status']);

    mysqli_query($ahk_conn, "UPDATE mphistory SET status='$status' WHERE id='$id'");
    $msg = "Status updated successfully!";

    // If Completed → send SMS
    if ($status == 2) {
        $row = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT dl_no, order_id, username, name FROM mphistory WHERE id='$id'"));
        $memberid = $row['dl_no'];
        $order = $row['order_id'];
        $membername = $row['name'] ?? '';
        $username = $row['username'] ?? '';

        sendSMS($memberid, $membername, $username);
    }
}

// =================================================
// FETCH ALL FMP RECORDS WHERE STATUS != 2
// =================================================
$result = mysqli_query($ahk_conn, "SELECT * FROM mphistory WHERE status != 2 ORDER BY id DESC");

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>FMP Update Panel</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>
</head>

<body>
<div class="container mt-5">
    <h4 class="text-center mb-4 text-primary">FMP Update Panel</h4>

    <?php if ($msg): ?>
        <script>
            Swal.fire({
                icon: "info",
                title: "Notice",
                text: <?php echo json_encode($msg); ?>
            });
        </script>
    <?php endif; ?>

    <table class="table table-bordered table-striped text-center align-middle">
        <thead class="table-dark">
            <tr>
                <th>ID</th>
                <th>Member ID</th>
                <th>Order ID</th>
                <th>Date</th>
                <th>Certificate</th>
                <th>Status</th>
                <th>Upload Certificate</th>
                <th>Update Status</th>
            </tr>
        </thead>

        <tbody>
            <?php while ($row = mysqli_fetch_assoc($result)): ?>
            <tr>
                <td><?= $row['id']; ?></td>
                <td><?= htmlspecialchars($row['dl_no']); ?></td>
                <td><?= htmlspecialchars($row['order_id']); ?></td>
                <td><?= htmlspecialchars($row['date']); ?></td>

                <td>
                    <?php if ($row['cert']): ?>
                        <a href="<?= htmlspecialchars($row['cert']); ?>" target="_blank" class="btn btn-sm btn-success">View</a>
                    <?php else: ?>
                        <span class="text-muted">N/A</span>
                    <?php endif; ?>
                </td>

                <td>
                    <?= ["Pending", "In Process", "Completed"][$row['status']] ?? "Unknown"; ?>
                </td>

                <td>
                    <form method="POST" enctype="multipart/form-data">
                        <input type="file" name="certificate" class="form-control mb-1" required>
                        <input type="hidden" name="history_id" value="<?= $row['id']; ?>">
                        <button type="submit" name="upload_cert" class="btn btn-success btn-sm w-100">
                            Upload
                        </button>
                    </form>
                </td>

                <td>
                    <form method="POST">
                        <select name="status" class="form-select mb-1">
                            <option value="0" <?= ($row['status']==0?'selected':''); ?>>Pending</option>
                            <option value="1" <?= ($row['status']==1?'selected':''); ?>>In Process</option>
                            <option value="2" <?= ($row['status']==2?'selected':''); ?>>Completed</option>
                        </select>

                        <input type="hidden" name="history_id" value="<?= $row['id']; ?>">
                        <button type="submit" name="update_status" class="btn btn-primary btn-sm w-100">
                            Update
                        </button>
                    </form>
                </td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>
</body>
</html>
