<?php
session_start();

require 'dbconn.php';


$adminId = $_SESSION['admin_id'];
$currentPassword = trim($_POST['current_password'] ?? '');
$newPassword     = trim($_POST['new_password'] ?? '');
$confirmPassword = trim($_POST['confirm_password'] ?? '');

// Basic validation
if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
    echo "<script>alert('All fields are required.'); window.history.back();</script>";
    exit;
}

if ($newPassword !== $confirmPassword) {
    echo "<script>alert('New and Confirm password do not match.'); window.history.back();</script>";
    exit;
}

// Get current password from DB
$stmt = $mysqli->prepare("SELECT pass FROM clinics WHERE id = ?");
$stmt->bind_param('i', $adminId);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $admin = $result->fetch_assoc();
    $dbPassword = $admin['pass'];

    // ⚠️ If you're not using hashing
    if ($currentPassword !== $dbPassword) {
        echo "<script>alert('Current password is incorrect.'); window.history.back();</script>";
        exit;
    }

    // Update to new password
    $update = $mysqli->prepare("UPDATE clinics SET pass = ? WHERE id = ?");
    $update->bind_param('si', $newPassword, $adminId);
    if ($update->execute()) {
        echo "<script>alert('Password changed successfully.'); window.location.href='dashboard.php';</script>";
        exit;
    } else {
        echo "<script>alert('Something went wrong. Please try again.'); window.history.back();</script>";
        exit;
    }
}

echo "<script>alert('User not found.'); window.history.back();</script>";
