<?php
/**
 * Admin Password Change API
 * Allows admin to change their password
 */

session_start();
require 'config.php';

header('Content-Type: application/json');

// Debug: Log session info
error_log('Admin Password API - Session ID: ' . (isset($_SESSION['admin_id']) ? $_SESSION['admin_id'] : 'NOT SET'));

// Check admin authentication
if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access - Session expired'
    ]);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($input['action'])) {
            echo json_encode([
                'success' => false,
                'message' => 'Action is required'
            ]);
            exit;
        }
        
        $action = $input['action'];
        
        if ($action === 'change_password') {
            // Validate required fields
            if (!isset($input['current_password']) || !isset($input['new_password']) || !isset($input['confirm_password'])) {
                echo json_encode([
                    'success' => false,
                    'message' => 'All fields are required'
                ]);
                exit;
            }
            
            $current_password = trim($input['current_password']);
            $new_password = trim($input['new_password']);
            $confirm_password = trim($input['confirm_password']);
            $admin_id = $_SESSION['admin_id'];
            
            // Validate input
            if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
                echo json_encode([
                    'success' => false,
                    'message' => 'All fields are required'
                ]);
                exit;
            }
            
            // Check if new passwords match
            if ($new_password !== $confirm_password) {
                echo json_encode([
                    'success' => false,
                    'message' => 'New passwords do not match'
                ]);
                exit;
            }
            
            // Check password length
            if (strlen($new_password) < 6) {
                echo json_encode([
                    'success' => false,
                    'message' => 'New password must be at least 6 characters'
                ]);
                exit;
            }
            
            // Get current admin password from database
            $sql = "SELECT password FROM admins WHERE id = " . intval($admin_id);
            error_log('Admin Password API - Query: ' . $sql);
            $result = $conn->query($sql);
            
            if (!$result || $result->num_rows === 0) {
                error_log('Admin Password API - Admin not found. Query result rows: ' . ($result ? $result->num_rows : 'NULL'));
                echo json_encode([
                    'success' => false,
                    'message' => 'Admin account not found'
                ]);
                exit;
            }
            
            $admin = $result->fetch_assoc();
            
            // Verify current password
            if (!password_verify($current_password, $admin['password'])) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Current password is incorrect'
                ]);
                exit;
            }
            
            // Check if new password is same as old password
            if (password_verify($new_password, $admin['password'])) {
                echo json_encode([
                    'success' => false,
                    'message' => 'New password cannot be the same as current password'
                ]);
                exit;
            }
            
            // Hash new password and update
            $hashed_password = password_hash($new_password, PASSWORD_BCRYPT);
            
            $update_sql = "UPDATE admins SET password = '" . $conn->real_escape_string($hashed_password) . "' WHERE id = " . intval($admin_id);
            error_log('Admin Password API - Update SQL: UPDATE admins SET password = *** WHERE id = ' . intval($admin_id));
            
            if ($conn->query($update_sql)) {
                error_log('Admin Password API - Password updated successfully for admin ID: ' . $admin_id);
                echo json_encode([
                    'success' => true,
                    'message' => 'Password changed successfully'
                ]);
            } else {
                $db_error = $conn->error;
                error_log('Admin Password API - Database error: ' . $db_error);
                echo json_encode([
                    'success' => false,
                    'message' => 'Error updating password'
                ]);
            }
            
        } else {
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action'
            ]);
        }
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => 'Error: ' . $e->getMessage()
        ]);
    }
}
?>
