<?php
require __DIR__ . '/email/class.phpmailer.php';
require __DIR__ . '/email/class.smtp.php';
include "database/config.php"; 

// Fetch programs and intakes for dropdowns
$programs = mysqli_query($conn, "SELECT `id`, `program` FROM `programs` WHERE 1");
$intakes = mysqli_query($conn, "SELECT `id`, `intake` FROM `intake` WHERE 1");

if (isset($_POST['register'])) {
    $studentname = mysqli_real_escape_string($conn, $_POST['studentname']);
    $studentid   = mysqli_real_escape_string($conn, $_POST['studentid']);
    $intake      = mysqli_real_escape_string($conn, $_POST['intake']);
    $start_year  = mysqli_real_escape_string($conn, $_POST['start_year']);
    $end_year    = mysqli_real_escape_string($conn, $_POST['end_year']);
    $program     = mysqli_real_escape_string($conn, $_POST['program']);
    $mobile      = mysqli_real_escape_string($conn, $_POST['mobile']);
    $email       = mysqli_real_escape_string($conn, $_POST['email']);
    $pass        = password_hash($_POST['pass'], PASSWORD_DEFAULT);
    $status      = 'active';

    // Handle image upload
    $image = 'default.png';
    if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $image = $studentid . "." . $ext;
        move_uploaded_file($_FILES['image']['tmp_name'], "students/img/" . $image);
    }

    // Insert into database
    $sql = "INSERT INTO students (`image`, `studentid`, `studentname`, `intake`, `start_year`, `end_year`, `program`, `mobile`, `email`, `pass`, `status`)
            VALUES ('$image', '$studentid', '$studentname', '$intake', '$start_year', '$end_year', '$program', '$mobile', '$email', '$pass', '$status')";

    if (mysqli_query($conn, $sql)) {
        $successMsg = "Registration successful! A confirmation email has been sent.";

        // PHPMailer SMTP
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host       = 'unicohsuniversity.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'no-reply@unicohsuniversity.com';
            $mail->Password   = '@mypass1996';
            $mail->SMTPSecure = 'tls';
            $mail->Port       = 587;

            $mail->setFrom('no-reply@unicohsuniversity.com', 'Unicohs University');
            $mail->addAddress($email, $studentname);

            $mail->isHTML(true);
            $mail->Subject = 'Registration Successful - Unicohs University Portal';
            $mail->Body    = "
                <h3>Welcome to Unicohs University!</h3>
                <p>Dear <strong>$studentname</strong>,</p>
                <p>Your registration has been successfully received.</p>
                <p><strong>Email:</strong> $email<br>
                <strong>Student ID:</strong> $studentid</p>
                 <strong>Password ID:</strong> *******</p>
                <p>Thank you for joining Unicohs University.</p>
            ";
            $mail->send();
        } catch (Exception $e) {
            $mailError = "Email could not be sent. Mailer Error: {$mail->ErrorInfo}";
        }
    } else {
        $errorMsg = "Error: " . mysqli_error($conn);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Registration - UniCoHS</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
<style>
body { font-family: 'Roboto', sans-serif; background: #f5f7fa; }
.card { border-radius: 20px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); padding: 30px; margin-top: 50px; }
h2 { color: var(--primary);; margin-bottom: 25px; font-weight: 700; }
.form-control { border-radius: 12px; padding: 12px; margin-bottom: 15px; }
.btn-primary { background: var(--primary);; border-radius: 12px; padding: 12px; font-weight: 600; width: 100%; }
.upload-container {
    border: 2px dashed #ccc;
    border-radius: 10px;
    padding: 20px;
    text-align: center;
    cursor: pointer;
    transition: border-color 0.3s;
}
.upload-container:hover {
    border-color:var(--primary);;
}
.upload-label { display: block; margin-bottom: 10px; font-weight: 500; }
.btn { background:var(--primary);; color:white; }
.preview-img { margin-top: 10px; max-width: 100%; height: auto; border-radius: 8px; border: 1px solid #ddd; }
</style>
</head>
<body>
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card">
                <h2 class="text-center">Student Registration</h2>

                <?php if(isset($successMsg)) echo "<div class='alert alert-success'>$successMsg</div>"; ?>
                <?php if(isset($mailError)) echo "<div class='alert alert-warning'>$mailError</div>"; ?>
                <?php if(isset($errorMsg)) echo "<div class='alert alert-danger'>$errorMsg</div>"; ?>

                <form method="post" enctype="multipart/form-data">
                    <center> 
                     <label class="upload-container">
                            <center>
                            <img id="preview" class="preview-img" src="#" alt="Image Preview" style="display:none;" width="100px">
                               </center>
                        Upload Profile Image
                        <input hidden type="file" name="image" accept="image/*" class="form-control" onchange="previewImage(event)">
                    </label>
                    </center>
                    
                    <input type="text" name="studentname" placeholder="Full Name" class="form-control" required>
                    <input type="text" name="studentid" placeholder="Student ID" class="form-control" required>

                    <!-- Intake Dropdown -->
                    <select name="intake" class="form-control" required>
                        <option value="">--Select Intake--</option>
                        <?php while($row = mysqli_fetch_assoc($intakes)) { ?>
                            <option value="<?php echo $row['intake']; ?>"><?php echo $row['intake']; ?></option>
                        <?php } ?>
                    </select>

                   <input type="number" name="start_year" placeholder="Start Year" min="2000" max="2100" class="form-control" required>
<input type="number" name="end_year" placeholder="End Year" min="2000" max="2100" class="form-control" required>


                    <!-- Program Dropdown -->
                    <select name="program" class="form-control" required>
                        <option value="">--Select Program--</option>
                        <?php while($row = mysqli_fetch_assoc($programs)) { ?>
                            <option value="<?php echo $row['program']; ?>"><?php echo $row['program']; ?></option>
                        <?php } ?>
                    </select>

                    <input type="text" name="mobile" placeholder=" Mobile Number" class="form-control" required>
                    <input type="email" name="email" placeholder="Email Address" class="form-control" required>
                    <input type="password" name="pass" placeholder="Password" class="form-control" required>

                    <button type="submit" name="register" class="btn btn-primary mt-2">Register</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function previewImage(event) {
    const reader = new FileReader();
    reader.onload = function() {
        const img = document.getElementById('preview');
        img.src = reader.result;
        img.style.display = 'block';
    }
    reader.readAsDataURL(event.target.files[0]);
}
</script>

</body>
</html>
