<?php
require_once 'db.php';

// Start session securely
session_start([
    'cookie_httponly' => true,
    'cookie_secure' => isset($_SERVER['HTTPS']),
    'cookie_samesite' => 'Strict'
]);

// Redirect only if fully authenticated
if (!empty($_SESSION['authenticated_user'])) {
    header("Location: /LoanApprovalPredction/Admin/index.php");
    exit;
}

// Generate CSRF token if not set
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Initialize message variables
$message = null;
$error = null;

// Handle Registration
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["next"])) {
    // Validate CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $error = "Invalid CSRF token!";
    } else {
        $email = trim($_POST["email"] ?? '');
        $phone = trim($_POST["phone"] ?? '');
        $members_name = trim($_POST["members_name"] ?? '');
        $address = trim($_POST["address"] ?? '');
        $password = $_POST["newpassword"] ?? '';
        $image = $_FILES["image"] ?? [];
        $mpid = 2; // Default MPid

        // Validate inputs
        if (!filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($email) > 50) {
            $error = "Please enter a valid email!";
        } elseif (!preg_match("/^\d{10}$|^\d{14}$/", $phone)) {
            $error = "Phone number must be 10 or 14 digits!";
        } elseif (empty($members_name)) {
            $error = "Please enter your name!";
        } elseif (strlen($password) < 8) {
            $error = "Password must be at least 8 characters!";
        } elseif (empty($image["name"]) || $image["error"] !== UPLOAD_ERR_OK) {
            $error = "Please select a valid profile image!";
        } else {
            // Check if user already exists
            $sql = "SELECT * FROM members WHERE Email = ? OR PhoneNo = ?";
            $stmt = mysqli_prepare($conn, $sql);
            mysqli_stmt_bind_param($stmt, "ss", $email, $phone);
            mysqli_stmt_execute($stmt);
            $result = mysqli_stmt_get_result($stmt);
            
            if (mysqli_num_rows($result) > 0) {
                $error = "Email or phone number already registered!";
            } else {
                $hashed_password = password_hash($password, PASSWORD_BCRYPT);
                $upload_dir = "images/";
                if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
                
                $image_path = $upload_dir . uniqid() . '_' . $image['name'];
                
                if (move_uploaded_file($image['tmp_name'], $image_path)) {
                    // Status is now 'verify' by default, OTP is NULL
                    $sql = "INSERT INTO members (Email, PhoneNo, MembersName, Address, PassKey, image, status, OTP, MPid) VALUES (?, ?, ?, ?, ?, ?, 'verify', NULL, ?)";
                    $stmt = mysqli_prepare($conn, $sql);
                    mysqli_stmt_bind_param($stmt, "ssssssi", $email, $phone, $members_name, $address, $hashed_password, $image_path, $mpid);
                    
                    if (mysqli_stmt_execute($stmt)) {
                        $message = "Registration successful! Redirecting to login...";
                    } else {
                        $error = "Registration failed. Please try again.";
                        unlink($image_path);
                    }
                } else {
                    $error = "Failed to upload image.";
                }
            }
            mysqli_stmt_close($stmt);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LoanApprovalPredction - Register</title>
    <link rel="icon" href="images/Approval.png" type="image/png">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .fade-in { animation: fadeIn 0.5s ease-in-out; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
    </style>
</head>
<body class="bg-gradient-to-br from-blue-50 to-gray-100 min-h-screen flex items-center justify-center font-sans">

    <div id="message-container" class="fixed top-4 left-1/2 transform -translate-x-1/2 z-50 max-w-md <?php echo ($message || $error) ? '' : 'hidden'; ?>">
        <?php if ($message): ?>
            <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded-lg shadow-md fade-in">
                <p><?php echo htmlspecialchars($message); ?></p>
            </div>
        <?php elseif ($error): ?>
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-lg shadow-md fade-in">
                <p><?php echo htmlspecialchars($error); ?></p>
            </div>
        <?php endif; ?>
    </div>

    <div class="w-full max-w-md p-8 bg-white rounded-xl shadow-2xl fade-in">
        <div class="flex items-center justify-center mb-6">
            <img src="images/Approval.png" alt="Logo" class="h-10 mr-2">
        </div>
        <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" enctype="multipart/form-data" class="space-y-5">
            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
            
            <div>
                <label class="block text-sm font-medium text-gray-700">Full Name</label>
                <input type="text" name="members_name" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" required>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700">Email</label>
                <input type="email" name="email" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" required>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700">Phone Number</label>
                <input type="tel" name="phone" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" required>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700">Address</label>
                <input type="text" name="address" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" required>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700">New Password</label>
                <input type="password" name="newpassword" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" required>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700">Profile Image</label>
                <input type="file" name="image" accept=".jpg,.jpeg,.png" class="w-full px-4 py-2 border rounded-lg text-sm" required>
            </div>

            <button type="submit" name="next" class="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">Register Now</button>
            
            <p class="text-center text-gray-600 mt-4">Already have an account? <a href="/LoanApprovalPredction/login.php" class="text-blue-600 hover:underline">Sign In</a></p>
        </form>
    </div>

    <script>
        // Redirect to login after 3 seconds if registration is successful
        <?php if ($message): ?>
            setTimeout(() => {
                window.location.href = "/LoanApprovalPredction/login.php";
            }, 3000);
        <?php endif; ?>

        // Hide messages after 5 seconds
        setTimeout(() => {
            const msg = document.getElementById('message-container');
            if (msg) msg.classList.add('hidden');
        }, 5000);
    </script>
</body>
</html>