<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
include("db.php"); // DB connection

$message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $first_name    = mysqli_real_escape_string($conn, $_POST['first_name']);
    $middle_name   = mysqli_real_escape_string($conn, $_POST['middle_name'] ?? '');
    $last_name     = mysqli_real_escape_string($conn, $_POST['last_name']);
    $dob           = mysqli_real_escape_string($conn, $_POST['dob']);
    $qualification = mysqli_real_escape_string($conn, $_POST['qualification']);
    $address       = mysqli_real_escape_string($conn, $_POST['address']);
    $mobile        = mysqli_real_escape_string($conn, $_POST['mobile']);
    $email         = mysqli_real_escape_string($conn, $_POST['email']);
    $password      = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $token         = bin2hex(random_bytes(16));

    // Check if email exists
    $check = mysqli_query($conn, "SELECT id FROM users WHERE email='$email'");
    if(mysqli_num_rows($check) > 0){
        $message = "<div class='alert alert-danger'>❌ Email already registered.</div>";
    } else {

        // Resume upload
        $resume_path = "";
        if (!empty($_FILES['resume']['name'])) {
            $target_dir = __DIR__ . "/uploads/resumes/";
            if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
            $resume_name = time() . "_" . basename($_FILES['resume']['name']);
            $resume_path = "uploads/resumes/" . $resume_name;
            move_uploaded_file($_FILES['resume']['tmp_name'], $target_dir . $resume_name);
        }

        // Insert user
        $query = "INSERT INTO users 
            (first_name, middle_name, last_name, date_of_birth, highest_qualification, resume, address, email, password, mobile_number, activation_token, is_active) 
            VALUES 
            ('$first_name', '$middle_name', '$last_name', '$dob', '$qualification', '$resume_path', '$address', '$email', '$password', '$mobile', '$token', 0)";

        if (mysqli_query($conn, $query)) {
            // Build activation link dynamically
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
            $domain = $_SERVER['HTTP_HOST'];
            $activation_link = $protocol . $domain . "/pharma_research/activate.php?token=$token";

            // Send activation email
            $to = $email;
            $subject = "Activate Your Pharma Research Account";
            $body = "<h2>Welcome, $first_name!</h2>
                     <p>Thank you for registering with <b>Pharma Research</b>.</p>
                     <p>Please click the link below to activate your account:</p>
                     <p><a href='$activation_link'>$activation_link</a></p>";
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= "From: Pharma Research <no-reply@" . $domain . ">" . "\r\n";

            if(mail($to, $subject, $body, $headers)){
                $message = "<div class='alert alert-success'>✅ Account created! Please check your email ($email) to activate your account.</div>";
            } else {
                $message = "<div class='alert alert-warning'>⚠️ Account created, but email could not be sent.</div>";
            }

        } else {
            $message = "<div class='alert alert-danger'>❌ Error: " . mysqli_error($conn) . "</div>";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Signup - Pharma Research</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
<style>
    body {
        background: linear-gradient(135deg, #74ebd5, #ACB6E5);
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        font-family: 'Segoe UI', sans-serif;
    }
    .signup-card {
        background: #ffffffcc;
        backdrop-filter: blur(10px);
        padding: 2rem;
        border-radius: 1rem;
        box-shadow: 0 0 30px rgba(0,0,0,0.2);
        max-width: 500px;
        width: 100%;
    }
    .signup-card h3 {
        font-weight: 700;
    }
    .form-control:focus {
        border-color: #5e72e4;
        box-shadow: 0 0 0 0.2rem rgba(94,114,228,0.25);
    }
    .btn-signup {
        background: #5e72e4;
        border: none;
    }
    .btn-signup:hover {
        background: #324cdd;
    }
    .input-group-text {
        background: #f0f2f5;
        border: none;
    }
    .password-toggle {
        cursor: pointer;
    }
    @media (max-width: 576px) {
        .signup-card {
            padding: 1.5rem;
        }
    }
</style>
</head>
<body>

<div class="signup-card text-center">
    <h3 class="mb-4 text-primary"><i class="bi bi-person-plus-fill"></i> Signup - Pharma Research</h3>

    <!-- Show messages -->
    <?php if (!empty($message)) echo $message; ?>

    <form method="POST" enctype="multipart/form-data">
        <div class="mb-3 input-group">
            <span class="input-group-text"><i class="bi bi-person-fill"></i></span>
            <input type="text" name="first_name" class="form-control" placeholder="First Name" required>
        </div>
        <div class="mb-3 input-group">
            <span class="input-group-text"><i class="bi bi-person-lines-fill"></i></span>
            <input type="text" name="middle_name" class="form-control" placeholder="Middle Name (optional)">
        </div>
        <div class="mb-3 input-group">
            <span class="input-group-text"><i class="bi bi-person-fill"></i></span>
            <input type="text" name="last_name" class="form-control" placeholder="Last Name" required>
        </div>
        <div class="mb-3 input-group">
            <span class="input-group-text"><i class="bi bi-calendar-fill"></i></span>
            <input type="date" name="dob" class="form-control" required>
        </div>
        <div class="mb-3 input-group">
            <span class="input-group-text"><i class="bi bi-mortarboard-fill"></i></span>
            <input type="text" name="qualification" class="form-control" placeholder="Highest Qualification" required>
        </div>
        <div class="mb-3">
            <label class="form-label">Upload Resume</label>
            <input type="file" name="resume" class="form-control">
        </div>
        <div class="mb-3">
            <label class="form-label">Address</label>
            <textarea name="address" class="form-control" placeholder="Address" required></textarea>
        </div>
        <div class="mb-3 input-group">
            <span class="input-group-text"><i class="bi bi-envelope-fill"></i></span>
            <input type="email" name="email" class="form-control" placeholder="Email ID" required>
        </div>
        <div class="mb-3 input-group">
            <span class="input-group-text"><i class="bi bi-lock-fill"></i></span>
            <input type="password" id="password" name="password" class="form-control" placeholder="Password (min 6 chars)" required minlength="6">
            <span class="input-group-text password-toggle" onclick="togglePassword()">
                <i id="toggleIcon" class="bi bi-eye-fill"></i>
            </span>
        </div>
        <div class="mb-3 input-group">
            <span class="input-group-text"><i class="bi bi-telephone-fill"></i></span>
            <input type="text" name="mobile" class="form-control" placeholder="Mobile Number" required>
        </div>

        <button type="submit" class="btn btn-signup w-100 py-2">Signup</button>
    </form>

    <p class="mt-3">Already have an account? <a href="login.php" class="text-primary fw-semibold">Login</a></p>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
function togglePassword() {
    const passwordField = document.getElementById('password');
    const toggleIcon = document.getElementById('toggleIcon');
    if (passwordField.type === 'password') {
        passwordField.type = 'text';
        toggleIcon.classList.replace('bi-eye-fill', 'bi-eye-slash-fill');
    } else {
        passwordField.type = 'password';
        toggleIcon.classList.replace('bi-eye-slash-fill', 'bi-eye-fill');
    }
}
</script>
</body>
</html>
