<?php

ob_start();
session_start();

error_reporting(E_ALL);
ini_set('display_errors',1);

if(
    !isset($_SESSION['role']) ||
    $_SESSION['role'] != "admin"
){
    die("Access Denied");
}

define("ROOT", $_SERVER['DOCUMENT_ROOT']."/SEAT");

include("../../../config/db.php");


/* ======================================================
   PHPMailer LOAD (FIXED FOR CPANEL - NO AUTLOAD)
====================================================== */

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require ROOT.'/vendor/PHPMailer/src/PHPMailer.php';
require ROOT.'/vendor/PHPMailer/src/SMTP.php';
require ROOT.'/vendor/PHPMailer/src/Exception.php';


/* ======================================================
   SEND EMAIL FUNCTION (CPANEL FIXED)
====================================================== */

function sendStatusMail($to, $subject, $message)
{
    $mail = new PHPMailer(true);

    try {

        $mail->isSMTP();

        /* ================= CPANEL SMTP ================= */
        $mail->Host = 'mail.mozabiz.com';
        $mail->SMTPAuth = true;

        $mail->Username = 'noreply@mozabiz.com';
        $mail->Password = 'Norshafiqa@241'; // email password

        /* USE SAME STYLE AS YOUR WORKING MODULE */
        $mail->Port = 465;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;

        $mail->SMTPDebug = 0;

        $mail->setFrom('noreply@mozabiz.com', 'SEAT System');
        $mail->addAddress($to);

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body = nl2br(htmlspecialchars($message));
        $mail->AltBody = $message;

        return $mail->send();

    } catch (Exception $e) {

        error_log("EMAIL ERROR: " . $mail->ErrorInfo);
        error_log("EXCEPTION: " . $e->getMessage());

        return false;
    }
}


/* ======================================================
   AJAX REQUEST
====================================================== */

if(
    $_SERVER['REQUEST_METHOD'] == "POST"
    && isset($_POST['ajax'])
){

    ob_clean();
    header('Content-Type: application/json');

    $id = intval($_POST['id']);
    $action = $_POST['action'] ?? '';

    /* ================= GET USER ================= */

    $res = mysqli_query(
        $conn,
        "SELECT email FROM users WHERE id=$id LIMIT 1"
    );

    if(!$res || mysqli_num_rows($res) == 0){

        echo json_encode([
            "status" => "error",
            "message" => "User not found"
        ]);
        exit;
    }

    $user = mysqli_fetch_assoc($res);
    $email = $user['email'];


    /* ======================================================
       APPROVE
    ====================================================== */

    if($action == "approve"){

        $pass = rand(100000,999999);
        $hash = password_hash($pass, PASSWORD_DEFAULT);

        $update = mysqli_query(
            $conn,
            "UPDATE users SET status='active', password='$hash' WHERE id=$id"
        );

        if(!$update){

            echo json_encode([
                "status" => "error",
                "message" => "Database update failed"
            ]);
            exit;
        }

        $mailSent = sendStatusMail(
            $email,
            "Account Approved",
            "Your organizer account has been approved.

Email: $email
Temporary Password: $pass

Please login and change your password immediately."
        );

        if(!$mailSent){

            echo json_encode([
                "status" => "error",
                "message" => "Account approved but email failed"
            ]);
            exit;
        }

        echo json_encode([
            "status" => "success",
            "message" => "Organizer approved successfully"
        ]);
        exit;
    }


    /* ======================================================
       REJECT
    ====================================================== */

    if($action == "reject"){

        $note = trim($_POST['note'] ?? '');
        $note = mysqli_real_escape_string($conn, $note);

        $delete = mysqli_query(
            $conn,
            "DELETE FROM users WHERE id=$id"
        );

        if(!$delete){

            echo json_encode([
                "status" => "error",
                "message" => "Delete failed"
            ]);
            exit;
        }

        $mailSent = sendStatusMail(
            $email,
            "Application Rejected",
            "Your organizer application has been rejected.

Reason:
$note"
        );

        if(!$mailSent){

            echo json_encode([
                "status" => "error",
                "message" => "User deleted but email failed"
            ]);
            exit;
        }

        echo json_encode([
            "status" => "success",
            "message" => "Organizer rejected successfully"
        ]);
        exit;
    }


    echo json_encode([
        "status" => "error",
        "message" => "Invalid action"
    ]);
    exit;
}


/* ======================================================
   FETCH ORGANIZER
====================================================== */

$id = intval($_GET['id'] ?? 0);

$q = mysqli_query(
$conn,
"
SELECT
    u.id AS user_id,
    u.email,
    u.role,
    u.status,

    o.club_name,
    o.club_type,
    o.advisor_name,
    o.advisor_phone,
    o.description,
    o.document

FROM users u
LEFT JOIN organizers o ON o.user_id = u.id
WHERE u.id = $id
LIMIT 1
"
);

if(!$q){
    die("Query Error: " . mysqli_error($conn));
}

$d = mysqli_fetch_assoc($q);

if(!$d){
    die("<h3>Organizer not found</h3>");
}


/* ======================================================
   BANK
====================================================== */

$bankQ = mysqli_query(
$conn,
"
SELECT *
FROM bank_accounts
WHERE user_id = $id
LIMIT 1
"
);

$bank = mysqli_fetch_assoc($bankQ);


/* ======================================================
   TEMPLATE
====================================================== */

include("../../../templates/header.php");
include("../../../templates/sidebar.php");

?>


<link rel="stylesheet" href="/SEAT/assets/css/admin/organizer_view.css">

<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap" rel="stylesheet">

<div class="mainLayout">

<h2 class="pageTitle">Review Organizer Application</h2>

<div class="centerWrap">
<div class="card">

<a href="manage_organizer.php" class="btn btnGray">← Back</a>

<div class="sectionTitle">Organization</div>

<div class="info-grid">

<div><label>Club Name</label><span><?= htmlspecialchars($d['club_name'] ?? '') ?></span></div>
<div><label>Type</label><span><?= htmlspecialchars($d['club_type'] ?? '') ?></span></div>
<div><label>Role</label><span><?= htmlspecialchars($d['role'] ?? '') ?></span></div>
<div><label>Email</label><span><?= htmlspecialchars($d['email'] ?? '') ?></span></div>

<div><label>Description</label>
<span><?= nl2br(htmlspecialchars($d['description'] ?? '')) ?></span></div>

<div><label>Status</label><span><?= htmlspecialchars($d['status'] ?? '') ?></span></div>

</div>


<div class="sectionTitle">Advisor</div>

<div class="info-grid">

<div><label>Name</label><span><?= htmlspecialchars($d['advisor_name'] ?? '') ?></span></div>
<div><label>Phone</label><span><?= htmlspecialchars($d['advisor_phone'] ?? '') ?></span></div>

</div>


<div class="sectionTitle">Bank Details</div>

<div class="info-grid">

<div><label>Account Holder</label><span><?= htmlspecialchars($bank['account_holder_name'] ?? 'N/A') ?></span></div>
<div><label>Bank Name</label><span><?= htmlspecialchars($bank['bank_name'] ?? 'N/A') ?></span></div>
<div><label>Account Number</label><span><?= htmlspecialchars($bank['account_number'] ?? 'N/A') ?></span></div>

</div>


<div class="sectionTitle">Document</div>

<div class="documentFooter">

<?php if(!empty($d['document'])): ?>
<a class="btn btnBlue"
href="/SEAT/uploads/club_register/<?= htmlspecialchars($d['document']) ?>"
target="_blank">View Document</a>
<?php else: ?>
<span>No document uploaded</span>
<?php endif; ?>

</div>


<?php if(($d['status'] ?? '') == "pending"): ?>

<div class="sectionTitle">Decision</div>

<form id="actionForm">

<input type="hidden" name="id" value="<?= $d['user_id'] ?>">

<textarea name="note" class="noteBox" placeholder="Reject note..."></textarea>

<div class="btnRow">

<button type="button" onclick="sendAction('approve')" class="btn btnGreen">Approve</button>
<button type="button" onclick="sendAction('reject')" class="btn btnRed">Reject</button>

</div>

</form>

<?php endif; ?>

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


<script>
function sendAction(action){

    let form = document.getElementById("actionForm");
    let formData = new FormData(form);

    formData.append("action", action);
    formData.append("ajax", "1");

    fetch(window.location.href, {
        method: "POST",
        body: formData
    })
    .then(res => res.json())
    .then(data => {

        alert(data.message);

        if(data.status === "success"){
            setTimeout(() => {
                window.location.href = "manage_organizer.php";
            }, 1500);
        }

    })
    .catch(err => {
        console.error(err);
        alert("Server error");
    });

}
</script>