<?php
session_start();
require 'dbconn.php'; // Provides $mysqli connection

// Grab & trim inputs
$email    = trim($_POST['email']    ?? '');
$password = trim($_POST['password'] ?? '');

// Basic validation
if (empty($email) || empty($password)) {
    echo "<script>alert('Email and password are required.'); window.history.back();</script>";
    exit;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "<script>alert('Invalid email format.'); window.history.back();</script>";
    exit;
}

// Query user by email (regardless of status)
$stmt = $mysqli->prepare("SELECT id, c_name, pass, status FROM clinics WHERE email = ? LIMIT 1");
$stmt->bind_param('s', $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows === 1) {
    $admin = $result->fetch_assoc();

    // Check password
    if (md5($password) !== $admin['pass']) {
        echo "<script>alert('Incorrect password.'); window.history.back();</script>";
        exit;
    }

    // Check status
    if (strtolower($admin['status']) !== 'active') {
        echo "<script>alert('Account is not active. Please contact support.'); window.history.back();</script>";
        exit;
    }

    // Successful login
    $_SESSION['clinic_logged_in'] = true;
    $_SESSION['clinic_name'] = $admin['c_name']; 
    $_SESSION['clinic_id'] = $admin['id'];       

    header('Location: dashboard.php');
    exit;
}

// If no user found with the email
echo "<script>alert('No account found with this email.'); window.history.back();</script>";
?>
