<?php
session_start();

// 1. Database Connection
$db_path = file_exists('includes/db.php') ? 'includes/db.php' : '../includes/db.php';
if (file_exists($db_path)) {
    require $db_path;
} else {
    $conn = new mysqli('localhost', 'root', '', 'bajipari');
}

// 2. Auth Check
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$msg = "";
$msg_type = "";

// --- HANDLE POST REQUESTS (Data Save) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Ensure profile entry exists
    $check = $conn->query("SELECT user_id FROM player_profiles WHERE user_id=$user_id");
    if($check->num_rows == 0){
        $conn->query("INSERT INTO player_profiles (user_id) VALUES ($user_id)");
    }

    // A. Update Text Info
    if (isset($_POST['action'])) {
        $val = $conn->real_escape_string($_POST['value']);
        
        if ($_POST['action'] == 'full_name') {
            $conn->query("UPDATE player_profiles SET kyc_real_name='$val' WHERE user_id=$user_id");
        } 
        elseif ($_POST['action'] == 'birthday') {
            $conn->query("UPDATE player_profiles SET kyc_dob='$val' WHERE user_id=$user_id");
        }
        elseif ($_POST['action'] == 'email') {
            // Updating email resets verification status
            $conn->query("UPDATE users SET email='$val', email_verified=0 WHERE id=$user_id");
        }
        header("Location: personal_info.php");
        exit();
    }

    // B. Handle Avatar Upload
    if (isset($_FILES['avatar']['name']) && $_FILES['avatar']['name'] != "") {
        $upload_dir = "assets/uploads/avatars/";
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);

        $ext = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];

        if (in_array($ext, $allowed)) {
            $new_filename = "avatar_" . $user_id . "." . $ext;
            foreach($allowed as $del_ext) {
                if(file_exists($upload_dir . "avatar_" . $user_id . "." . $del_ext)) {
                    unlink($upload_dir . "avatar_" . $user_id . "." . $del_ext);
                }
            }
            move_uploaded_file($_FILES['avatar']['tmp_name'], $upload_dir . $new_filename);
        }
        header("Location: personal_info.php");
        exit();
    }

    // C. SEND OTP (PHPMailer)
    if (isset($_POST['send_otp'])) {
        $email = $_POST['email_to_verify'];
        $otp = rand(100000, 999999);
        $_SESSION['email_otp'] = $otp;
        
        // --- PHPMailer Configuration ---
        // Adjust paths as per your directory structure
        require '../includes/PHPMailer/src/Exception.php';
        require '../includes/PHPMailer/src/PHPMailer.php';
        require '../includes/PHPMailer/src/SMTP.php';

        $mail = new PHPMailer\PHPMailer\PHPMailer(true);

        try {
            // SMTP Settings
            $mail->isSMTP();
            $mail->Host       = 'mail.ruposhi88.com'; 
            $mail->SMTPAuth   = true;
            $mail->Username   = 'support@ruposhi88.com'; // YOUR EMAIL
            $mail->Password   = 'SuPPoRtRuPoshi88';    // YOUR APP PASSWORD
            $mail->SMTPSecure = 'ssl';
            $mail->Port       = 465;

            $mail->setFrom('support@ruposhi88.com', 'Ruposhi88 Support');
            $mail->addAddress($email);

            $mail->isHTML(true);
            $mail->Subject = 'Email Verification OTP';
            $mail->Body    = "Your verification code is: <b>$otp</b>";

            $mail->send();
            $msg = "OTP sent to $email!";
            $msg_type = "success";
        } catch (Exception $e) {
            $msg = "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
            $msg_type = "error";
        }
    }

    // D. VERIFY OTP
    if (isset($_POST['verify_otp'])) {
        $user_otp = $_POST['otp_code'];
        if (isset($_SESSION['email_otp']) && $user_otp == $_SESSION['email_otp']) {
            $conn->query("UPDATE users SET email_verified=1 WHERE id=$user_id");
            unset($_SESSION['email_otp']);
            $msg = "Email verified successfully!";
            $msg_type = "success";
        } else {
            $msg = "Invalid OTP!";
            $msg_type = "error";
        }
    }
}

// --- FETCH DATA ---
$sql = "SELECT u.username, u.phone, u.email, u.email_verified, u.created_at, 
               p.kyc_real_name, p.kyc_dob, p.kyc_status 
        FROM users u 
        LEFT JOIN player_profiles p ON u.id = p.user_id 
        WHERE u.id = $user_id";
$user = $conn->query($sql)->fetch_assoc();

// Check what is missing
$missing_personal = [];
if (empty($user['kyc_real_name'])) $missing_personal[] = "Full Name";
if (empty($user['kyc_dob']) || $user['kyc_dob'] == '0000-00-00') $missing_personal[] = "Birthday";

$missing_contact = [];
if ($user['kyc_status'] != 'verified') $missing_contact[] = "Phone Number"; 
if (empty($user['email'])) $missing_contact[] = "Email";

$show_info_box = !empty($missing_personal) || !empty($missing_contact);

// Avatar
$avatar_url = "";
$possible_exts = ['jpg', 'jpeg', 'png', 'webp'];
foreach ($possible_exts as $ext) {
    if (file_exists("assets/uploads/avatars/avatar_" . $user_id . "." . $ext)) {
        $avatar_url = "assets/uploads/avatars/avatar_" . $user_id . "." . $ext;
        break;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Personal Info</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">

    <style>
        body { background-color: #121619; color: #d1d5db; font-family: 'Roboto', sans-serif; padding-bottom: 90px; }
        .header-bg { background-color: #181c20; }

        /* Profile Card */
        .profile-card {
            background: linear-gradient(180deg, #2c353b 0%, #181c20 100%);
            border-radius: 8px; overflow: hidden; text-align: center;
            border: 1px solid #2f3840; position: relative;
        }
        .profile-bg {
            height: 90px;
            background: radial-gradient(circle, #c5a059 0%, #181c20 90%);
            opacity: 0.7;
        }
        
        .avatar-box {
            width: 70px; height: 70px;
            border-radius: 50%;
            background-color: #d1d5db;
            border: 4px solid #181c20;
            margin: -35px auto 5px auto;
            position: relative; z-index: 10;
            display: flex; align-items: center; justify-content: center;
            overflow: hidden; cursor: pointer;
        }
        .avatar-box img { width: 100%; height: 100%; object-fit: cover; }

        /* Logic-based Info Container */
        .info-container {
            background-color: #181c20;
            border: 1px solid #2f3840;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
            <?php echo (!$show_info_box) ? 'display: none;' : ''; ?>
        }

        /* List Items */
        .list-row {
            display: flex; justify-content: space-between; align-items: center;
            padding: 15px 0; border-bottom: 1px solid #232a31;
        }
        .list-row:last-child { border-bottom: none; }
        
        .row-left { display: flex; align-items: center; gap: 12px; }
        .row-icon { color: #d97706; font-size: 18px; width: 20px; text-align: center; }
        .row-title { color: #e5e7eb; font-size: 14px; font-weight: 500; }
        .row-sub { font-size: 11px; color: #6b7280; margin-top: 2px; }

        .btn-gold {
            background: linear-gradient(to bottom, #fcd34d, #d97706);
            color: white; font-weight: bold; font-size: 12px;
            padding: 6px 20px; border-radius: 4px; border: none;
            box-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }
        .btn-red {
            background: linear-gradient(to bottom, #ef4444, #b91c1c);
            color: white; font-weight: bold; font-size: 11px;
            padding: 6px 10px; border-radius: 4px;
            cursor: pointer;
        }
        .btn-green {
            background: linear-gradient(to bottom, #10b981, #059669); 
            color: white; font-weight: bold; font-size: 11px;
            padding: 6px 10px; border-radius: 4px; 
            cursor: default;
        }

        .pill { font-size: 10px; padding: 2px 10px; border-radius: 12px; margin-top: 5px; display: inline-block; background: #232a31; color: #6b7280; }
        .bottom-nav { background-color: #000; border-top: 1px solid #222; }
        .nav-item { color: #6b7280; } .nav-item.active { color: #facc15; }
    </style>
</head>
<body>

    <div class="header-bg p-4 flex justify-between items-center sticky top-0 z-50">
        <a href="index.php" class="text-white text-xl"><i class="fas fa-home"></i></a>
        <h1 class="text-white font-medium text-lg">Personal Info</h1>
        <button onclick="window.history.back()" class="text-white text-lg"><i class="fas fa-times"></i></button>
    </div>

    <div class="px-4 mt-4">
        
        <?php if($msg): ?>
            <div class="<?php echo $msg_type=='success' ? 'bg-green-900/50 text-green-400 border-green-600' : 'bg-red-900/50 text-red-400 border-red-600'; ?> border p-3 rounded mb-4 text-center text-sm">
                <?php echo $msg; ?>
            </div>
        <?php endif; ?>

        <div class="profile-card">
            <div class="profile-bg"></div>
            
            <form id="imgForm" method="POST" enctype="multipart/form-data" class="hidden">
                <input type="file" name="avatar" id="avatarInput" accept="image/*" onchange="document.getElementById('imgForm').submit()">
            </form>

            <div class="avatar-box" onclick="document.getElementById('avatarInput').click()">
                <?php if($avatar_url): ?>
                    <img src="<?php echo $avatar_url; ?>?t=<?php echo time(); ?>">
                <?php else: ?>
                    <i class="fas fa-user text-gray-500 text-3xl"></i>
                <?php endif; ?>
            </div>

            <div class="pb-3">
                <h2 class="text-white font-bold text-lg flex justify-center items-center gap-2">
                    <?php echo $user['username']; ?>
                    <span class="bg-[#323028] text-[#a19d8e] text-[9px] px-1.5 py-0.5 rounded border border-[#4a473e]">Normal</span>
                </h2>
                <p class="text-[10px] text-gray-500 mt-1">Date Registered : <?php echo date('Y/m/d', strtotime($user['created_at'])); ?></p>
            </div>

            <div class="bg-[#1e252b] border-t border-[#2f3840] p-3 flex justify-between items-center text-xs">
                <span class="text-gray-300">VIP Points (VP) <span class="text-[#facc15] ml-2 font-bold">0</span></span>
                <a href="vip.php" class="text-gray-400 flex items-center gap-1 hover:text-white">
                    My VIP <i class="fas fa-angle-double-right"></i>
                </a>
            </div>
        </div>

        <?php if($show_info_box): ?>
        <div class="info-container">
            <div class="flex justify-between items-start mb-3">
                <div class="flex gap-2">
                    <i class="fas fa-info-circle text-white mt-0.5 text-sm"></i>
                    <p class="text-gray-300 text-xs leading-snug">
                        Please complete the verification below before you proceed with the withdrawal request.
                    </p>
                </div>
                <i class="fas fa-chevron-up text-gray-500 text-xs"></i>
            </div>

            <div class="border-b border-[#2f3840] mb-3"></div>

            <div class="space-y-3">
                
                <?php if(!empty($missing_personal)): ?>
                <div>
                    <div class="border-l-2 border-[#10b981] pl-2 text-[13px] text-[#10b981] font-medium leading-none">Personal Info</div>
                    <div class="ml-3">
                        <?php foreach($missing_personal as $mp): ?>
                            <span class="pill mr-1"><?php echo $mp; ?></span>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <?php if(!empty($missing_contact)): ?>
                <div>
                    <div class="border-l-2 border-[#3b82f6] pl-2 text-[13px] text-[#3b82f6] font-medium leading-none">Contact Info</div>
                    <div class="ml-3">
                        <?php foreach($missing_contact as $mc): ?>
                            <span class="pill mr-1" style="background:rgba(59,130,246,0.15); color:#3b82f6"><?php echo $mc; ?></span>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

            </div>
        </div>
        <?php endif; ?>

        <div class="mt-4">
            
            <div class="list-row">
                <div class="row-left">
                    <i class="far fa-user-circle row-icon"></i>
                    <span class="row-title">Full Name</span>
                </div>
                <div>
                    <?php if(!empty($user['kyc_real_name'])): ?>
                        <span class="text-white text-sm font-bold"><?php echo $user['kyc_real_name']; ?></span>
                    <?php else: ?>
                        <button onclick="openModal('Full Name', 'full_name', 'text')" class="btn-gold">Add</button>
                    <?php endif; ?>
                </div>
            </div>

            <div class="list-row">
                <div class="row-left">
                    <i class="fas fa-birthday-cake row-icon"></i>
                    <span class="row-title">Birthday</span>
                </div>
                <div>
                    <?php if(!empty($user['kyc_dob']) && $user['kyc_dob'] != '0000-00-00'): ?>
                        <span class="text-white text-sm font-bold"><?php echo $user['kyc_dob']; ?></span>
                    <?php else: ?>
                        <button onclick="openModal('Birthday', 'birthday', 'date')" class="btn-gold">Add</button>
                    <?php endif; ?>
                </div>
            </div>

            <div class="list-row">
                <div class="row-left items-start">
                    <i class="fas fa-phone-alt row-icon mt-1"></i>
                    <div>
                        <span class="row-title block">Phone Number</span>
                        <span class="row-sub block"><?php echo $user['phone']; ?></span>
                    </div>
                </div>
                <div>
                    <?php if($user['kyc_status'] == 'verified'): ?>
                        <span class="text-[#10b981] text-xs font-bold"><i class="fas fa-check-circle"></i> Verified</span>
                    <?php else: ?>
                        <button class="btn-red">Not Verified</button>
                    <?php endif; ?>
                </div>
            </div>

            <div class="list-row">
                <div class="row-left items-start">
                    <i class="far fa-envelope row-icon mt-1"></i>
                    <div>
                        <span class="row-title block">Email</span>
                        <?php if(!empty($user['email'])): ?>
                            <span class="row-sub block"><?php echo $user['email']; ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <div>
                    <?php if(empty($user['email'])): ?>
                        <button onclick="openModal('Email', 'email', 'email')" class="btn-gold">Add</button>
                    <?php elseif($user['email_verified'] == 1): ?>
                        <button class="btn-green"><i class="fas fa-check-circle"></i> Verified</button>
                    <?php else: ?>
                        <div class="flex gap-2">
                            <button onclick="openVerifyModal('<?php echo $user['email']; ?>')" class="btn-red">Verify</button>
                            <button onclick="openModal('Email', 'email', 'email')" class="text-gray-500 text-xs"><i class="fas fa-edit"></i></button>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

        </div>

        <div class="mt-6 flex gap-3 text-[10px] text-gray-500 items-start px-2">
            <div class="w-6 h-6 rounded-full border border-gray-600 flex items-center justify-center flex-shrink-0">
                <i class="fas fa-headset text-gray-400 text-xs"></i>
            </div>
            <p>For privacy and security, Information can't modified after confirmation. Please <a href="support_chat.php" class="text-[#d97706] hover:underline">contact customer service</a> .</p>
        </div>

    </div>

    <div id="editModal" class="fixed inset-0 z-[100] hidden bg-black/80 flex items-center justify-center p-4 backdrop-blur-sm">
        <div class="bg-[#1c2227] w-full max-w-xs rounded-lg p-5 border border-gray-700 relative">
            <button onclick="document.getElementById('editModal').classList.add('hidden')" class="absolute top-3 right-3 text-gray-400"><i class="fas fa-times"></i></button>
            <h3 class="text-white text-lg font-bold mb-4" id="modalTitle">Add Info</h3>
            
            <form method="POST">
                <input type="hidden" name="action" id="modalAction">
                <div class="mb-4">
                    <input type="text" name="value" id="modalInput" class="w-full bg-[#121619] border border-gray-600 text-white rounded p-3 focus:outline-none focus:border-[#facc15]" required>
                </div>
                <button type="submit" class="w-full btn-gold py-3 text-sm">Save</button>
            </form>
        </div>
    </div>

    <div id="verifyModal" class="fixed inset-0 z-[100] hidden bg-black/80 flex items-center justify-center p-4 backdrop-blur-sm">
        <div class="bg-[#1c2227] w-full max-w-xs rounded-lg p-5 border border-gray-700 relative">
            <button onclick="document.getElementById('verifyModal').classList.add('hidden')" class="absolute top-3 right-3 text-gray-400"><i class="fas fa-times"></i></button>
            <h3 class="text-white text-lg font-bold mb-2">Email Verification</h3>
            <p class="text-xs text-gray-400 mb-4">Click 'Send Code' to receive an OTP at <br><span id="verifyEmailText" class="text-white font-bold"></span></p>
            
            <form method="POST" id="sendOtpForm">
                <input type="hidden" name="send_otp" value="1">
                <input type="hidden" name="email_to_verify" id="emailToVerifyInput">
                <button type="submit" class="w-full bg-blue-600 text-white py-2 rounded text-xs font-bold mb-4 hover:bg-blue-700 transition">Send Code</button>
            </form>

            <div class="border-t border-gray-700 my-3"></div>

            <form method="POST">
                <input type="hidden" name="verify_otp" value="1">
                <div class="mb-4">
                    <input type="text" name="otp_code" placeholder="Enter 6-digit Code" class="w-full bg-[#121619] border border-gray-600 text-white rounded p-3 text-center tracking-widest focus:outline-none focus:border-[#facc15]" required maxlength="6">
                </div>
                <button type="submit" class="w-full btn-gold py-3 text-sm">Verify Now</button>
            </form>
        </div>
    </div>

    <div class="fixed bottom-0 left-0 w-full h-[60px] bottom-nav z-50 flex justify-between items-center px-6">
        <a href="index.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-home text-lg mb-1"></i>
            <span class="text-[10px]">Home</span>
        </a>
        <a href="promotions.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-gift text-lg mb-1"></i>
            <span class="text-[10px]">Promotions</span>
        </a>
        <a href="deposit.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-wallet text-lg mb-1"></i>
            <span class="text-[10px]">Deposit</span>
        </a>
        <a href="account.php" class="flex flex-col items-center justify-center nav-item active">
            <i class="fas fa-user text-lg mb-1"></i>
            <span class="text-[10px]">My Account</span>
        </a>
    </div>

    <script>
        function openModal(title, action, type) {
            const modal = document.getElementById('editModal');
            document.getElementById('modalTitle').innerText = 'Add ' + title;
            document.getElementById('modalAction').value = action;
            
            const input = document.getElementById('modalInput');
            input.type = type;
            input.value = '';
            input.placeholder = 'Enter ' + title;
            
            modal.classList.remove('hidden');
        }

        function openVerifyModal(email) {
            document.getElementById('verifyEmailText').innerText = email;
            document.getElementById('emailToVerifyInput').value = email;
            document.getElementById('verifyModal').classList.remove('hidden');
        }
    </script>

</body>
</html>