<?php
session_start();
include('includes/config.php');

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    
    // Check if email exists
    $sql = "SELECT * FROM admins WHERE email = '$email' AND is_active = 1";
    $result = mysqli_query($conn, $sql);
    
    if (mysqli_num_rows($result) > 0) {
        $admin = mysqli_fetch_assoc($result);
        $admin_name = $admin['name'] ?: $admin['username'] ?: 'Administrator';
        $admin_id = $admin['id'];
        
        // Generate reset token
        $token = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
        $expires_timestamp = strtotime($expires);
        
        // Store token in database (you need to add reset_token and reset_expires columns to admins table)
        $update_sql = "UPDATE admins SET reset_token = '$token', reset_expires = '$expires' WHERE id = '{$admin['id']}'";
        mysqli_query($conn, $update_sql);
        
        // Get site URL dynamically
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        $host = $_SERVER['HTTP_HOST'];
        $base_url = $protocol . $host;
        $reset_link = $base_url . "/admin/reset_password.php?token=$token";
        
        // NOTIFICATION: Password Reset Request (ADMIN)
        $mail_subject = "Admin Password Reset Request";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Hello <span class='user-name'>" . $admin_name . "</span>,</h2>
                            
                            <p class='message'>
                                We received a request to reset your password for the <strong>" . $sitename . " Admin Panel</strong>.
                                Click the button below to create a new password.
                            </p>

                            <!-- Reset Button -->
                            <div class='action-section'>
                                <a href='" . $reset_link . "' class='action-button' style='display: inline-block; padding: 16px 45px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 17px;'>
                                    Reset Password
                                </a>
                            </div>

                            <!-- Link Alternative -->
                            <div class='link-alternative'>
                                <p style='color: #6c757d; margin-bottom: 5px;'>If the button doesn't work, copy and paste this link:</p>
                                <a href='" . $reset_link . "' class='verification-link'>" . $reset_link . "</a>
                            </div>

                            <!-- Security Information -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>🔒 Important Security Information</h4>
                                <ul style='color: #856404;'>
                                    <li><strong>This link expires in 1 hour</strong> (on " . date('F j, Y \a\t g:i A', $expires_timestamp) . ")</li>
                                    <li>If you didn't request this, please ignore this email</li>
                                    <li>Never share this link with anyone</li>
                                    <li>Our staff will never ask for your password</li>
                                </ul>
                            </div>

                            <!-- Request Details -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>📋 Request Details</h4>
                                <p style='color: #0056b3;'>
                                    <strong>Date & Time:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "<br>
                                    <strong>Browser:</strong> " . substr($_SERVER['HTTP_USER_AGENT'], 0, 100) . "...<br>
                                    <strong>Device:</strong> " . (is_mobile() ? 'Mobile' : 'Desktop') . "<br>
                                    <strong>Location:</strong> " . get_client_location() . "
                                </p>
                            </div>

                            <!-- What Happens Next -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>What Happens Next?</h3>
                                <ol style='color: #6c757d;'>
                                    <li><strong>Click the reset button</strong> above to create a new password</li>
                                    <li><strong>Choose a strong password</strong> (minimum 8 characters with mix of letters, numbers, and symbols)</li>
                                    <li><strong>Login with your new password</strong> immediately after reset</li>
                                    <li><strong>Keep your new password secure</strong> and never share it</li>
                                </ol>
                            </div>

                            <!-- Didn't Request This? -->
                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #721c24;'>⚠️ Didn't Request This?</h4>
                                <p style='color: #721c24;'>
                                    If you did not request a password reset, please:<br>
                                    1. <strong>Change your password immediately</strong> if you suspect unauthorized access<br>
                                    2. <strong>Contact the system administrator</strong><br>
                                    3. <strong>Review recent admin activity</strong> for any suspicious actions<br><br>
                                    <a href='" . $base_url . "/admin/contact.php' style='color: #721c24; font-weight: bold;'>Report Unauthorized Activity →</a>
                                </p>
                            </div>

                            <!-- Admin Panel Note -->
                            <div class='notice-box security'>
                                <div class='notice-title security'>🛡️ Admin Panel Security</div>
                                <div class='notice-text security'>
                                    This is an automated security notification from the " . $sitename . " Admin Panel.
                                    For security reasons, this password reset link can only be used once and expires in 1 hour.
                                </div>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Having trouble resetting your password?</p>
                                <a href='" . $base_url . "/admin/contact.php' class='support-link'>Contact System Administrator</a>
                                <p style='color: #6c757d; font-size: 13px; margin-top: 15px;'>
                                    <strong>Admin ID:</strong> " . $admin_id . "<br>
                                    <strong>Request Time:</strong> " . date('Y-m-d H:i:s') . "
                                </p>
                            </div>
                        </div>

                        <!-- Footer -->
                        <div class='email-footer'>
                            <img src='" . $myUrl . "/images/" . $sitelogo . "' alt='" . $sitename . "' class='footer-logo' />
                            <p class='copyright'>
                                &copy; " . date('Y') . " " . $sitename . ". All rights reserved.<br>
                                This is an automated security message from the Admin Panel.<br>
                                Admin Login: " . $base_url . "/admin/login.php
                            </p>
                        </div>";

        // Send admin notification using your mail system
        $user_email = $email;
        $first_name = $admin_name;
        include("mail/mail_sender.php");  // Adjust path as needed
        
        $success = "Password reset instructions have been sent to your email. Please check your inbox and spam folder.";
    } else {
        $error = "No account found with that email address or account is inactive.";
    }
}

// Helper functions for email
function is_mobile() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $mobile_devices = ['Mobile', 'Android', 'iPhone', 'iPad', 'webOS', 'BlackBerry', 'Windows Phone'];
    foreach ($mobile_devices as $device) {
        if (stripos($user_agent, $device) !== false) {
            return true;
        }
    }
    return false;
}

function get_client_location() {
    // You can implement IP geolocation here
    // For now, return a generic message
    $ip = $_SERVER['REMOTE_ADDR'];
    if ($ip == '127.0.0.1' || $ip == '::1') {
        return 'Localhost';
    }
    return 'Location detected via IP';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../images/favicon.ico">

    <title>AI Trading - Forgot Password</title>
  
	<!-- Vendors Style-->
	<link rel="stylesheet" href="css/vendors_css.css">
	  
	<!-- Style-->  
	<link rel="stylesheet" href="css/style.css">
	<link rel="stylesheet" href="css/skin_color.css">
	
	<!-- Font Awesome -->
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

</head>
	
<body class="hold-transition theme-primary bg-img" style="background-image: url(../images/auth-bg/bg-3.jpg)">
	
	<div class="container h-p100">
		<div class="row align-items-center justify-content-md-center h-p100">	
			
			<div class="col-12">
				<div class="row justify-content-center g-0">
					<div class="col-lg-5 col-md-5 col-12">
						<div class="bg-white rounded10 shadow-lg">
							<div class="content-top-agile p-20 pb-0">
								<div class="text-center">
									<img src="../images/logo-dark-text.png" alt="Logo" class="mb-3" style="height: 40px;">
									<h3 class="text-primary">Forgot Password</h3>
									<p class="mb-0">Enter your email to reset password</p>
								</div>						
							</div>
							<div class="p-40">
								<?php if ($success): ?>
									<div class="alert alert-success alert-dismissible fade show">
										<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
										<i class="fas fa-check-circle me-2"></i> <?php echo $success; ?>
									</div>
								<?php endif; ?>
								
								<?php if ($error): ?>
									<div class="alert alert-danger alert-dismissible fade show">
										<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
										<i class="fas fa-exclamation-circle me-2"></i> <?php echo $error; ?>
									</div>
								<?php endif; ?>
								
								<form action="" method="POST">
									<div class="form-group">
										<label class="form-label">Email Address <span class="text-danger">*</span></label>
										<div class="input-group mb-3">
											<span class="input-group-text bg-transparent"><i class="fas fa-envelope"></i></span>
											<input type="email" class="form-control ps-15 bg-transparent" name="email" placeholder="admin@example.com" required>
										</div>
									</div>
									
									<div class="row mt-30">
										<div class="col-6">
											<a href="login.php" class="btn btn-light w-100">
												<i class="fas fa-arrow-left me-2"></i> Back to Login
											</a>
										</div>
										<div class="col-6">
											<button type="submit" class="btn btn-primary w-100">
												<i class="fas fa-paper-plane me-2"></i> Send Reset Link
											</button>
										</div>
									</div>
								</form>
								
								<div class="text-center mt-30">
									<div class="alert alert-info">
										<i class="fas fa-info-circle me-2"></i>
										<small>You will receive an email with instructions to reset your password.</small>
									</div>
								</div>
							</div>						
						</div>
						
						<div class="text-center mt-20">
							<p class="text-white">
								<i class="fas fa-lock me-1"></i> Secure Password Recovery
							</p>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- Vendor JS -->
	<script src="js/vendors.min.js"></script>
	<script src="../assets/icons/feather-icons/feather.min.js"></script>
	
	<style>
	.alert-info {
		background: rgba(13, 202, 240, 0.1);
		border-color: rgba(13, 202, 240, 0.3);
	}
	</style>
	
</body>
</html>