<?php

// session_start();
// require 'config.php';
// require_once "../../../controllers/core/inc.login.php";
// require_once "../../../controllers/config/db_con_live_static.php";


// // Check if Azure AD returned an error
// if (isset($_GET['error'])) {
//     echo "<h2>Login failed</h2>";
//     echo "Error: " . htmlspecialchars($_GET['error']) . "<br>";
//     echo "Description: " . htmlspecialchars($_GET['error_description'] ?? '') . "<br>";
//     exit;
// }

// // Check if authorization code is present
// if (!isset($_GET['code'])) {
//     echo "No authorization code received.";
//     exit;
// }

// $code = $_GET['code'];
// echo "Authorization Code: " . htmlspecialchars($code) . "<br>";



// // Prepare data to exchange authorization code for tokens
// $post_fields = [
//     'client_id' => $client_id,
//     'scope' => $scope,
//     'code' => $code,
//     'redirect_uri' => $redirect_uri,
//     'grant_type' => 'authorization_code',
//     'client_secret' => $client_secret,
// ];

// // echo "<h2>POST Data Being Sent</h2>";
// // echo "<pre>" . htmlspecialchars(http_build_query($post_fields)) . "</pre>";

// // Initialize cURL request
// $curl = curl_init($token_url);
// curl_setopt($curl, CURLOPT_POST, true);
// curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_fields));
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // Only for testing
// curl_setopt($curl, CURLOPT_VERBOSE, true); // Enable verbose output

// // Execute cURL and get response
// $response = curl_exec($curl);

// // Check for cURL errors
// if (curl_error($curl)) {
//     echo "<h2>cURL Error</h2>";
//     echo "Error: " . curl_error($curl) . "<br>";
//     echo "Error Code: " . curl_errno($curl) . "<br>";
// }

// // Get HTTP status code
// $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);


// curl_close($curl);



// // Try to decode JSON response
// $token_data = json_decode($response, true);

// if (json_last_error() !== JSON_ERROR_NONE) {
//     echo "<h2>JSON Decode Error</h2>";
//     echo "Error: " . json_last_error_msg() . "<br>";
// }

// echo "<h2>Decoded Token Response</h2>";
// echo "<pre>" . htmlspecialchars(json_encode($token_data, JSON_PRETTY_PRINT)) . "</pre>";

// // Function to decode JWT token (basic decoding - not verifying signature)
// function decodeJWT($jwt) {
//     $parts = explode('.', $jwt);
//     if (count($parts) !== 3) {
//         return false;
//     }
    
//     $payload = base64_decode(strtr($parts[1], '-_', '+/'));
//     return json_decode($payload, true);
// }

// // Decode the ID token to get user info
// if (isset($token_data['id_token'])) {
//     $id_token = $token_data['id_token'];
//     $user_claims = decodeJWT($id_token);
    
//     if ($user_claims) {
//         echo "<h2>User Info from ID Token</h2>";
//         echo "Email: " . htmlspecialchars($user_claims['email'] ?? 'N/A') . "<br>";
//         echo "Name: " . htmlspecialchars($user_claims['name'] ?? 'N/A') . "<br>";
//         echo "Preferred Username: " . htmlspecialchars($user_claims['preferred_username'] ?? 'N/A') . "<br>";
//         echo "User ID (OID): " . htmlspecialchars($user_claims['oid'] ?? 'N/A') . "<br>";

       
// if(check_for_login('Robi','remonsarwar@gmail.com','V09VTUNOUU95RmxqR053eENoZG1vQT09',1)){}
        
//         // Store in session
//         $_SESSION['user_email'] = $user_claims['email'] ?? '';
//         $_SESSION['user_name'] = $user_claims['name'] ?? '';
//         $_SESSION['user_id'] = $user_claims['oid'] ?? '';
//         $_SESSION['access_token'] = $token_data['access_token'];
        
//         echo "<h3>All Claims:</h3>";
//         echo "<pre>" . htmlspecialchars(json_encode($user_claims, JSON_PRETTY_PRINT)) . "</pre>";
//     }
// }


?>
<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
// session_start();
// require 'config.php';
// require_once "../../../controllers/routing/default_values.php";
//  require_once "../../../controllers/config/check_login.php";
// require_once "../../../controllers/config/db_con_live_static.php";


// // Check if Azure AD returned an error
// if (isset($_GET['error'])) {
//     // echo "<h2>Login failed</h2>";
//     // echo "Error: " . htmlspecialchars($_GET['error']) . "<br>";
//     // echo "Description: " . htmlspecialchars($_GET['error_description'] ?? '') . "<br>";
//                                     $msg = "Sometning went wrong !!!";
//             $_SESSION['login_error'] = $msg; // optional: pass error via session
//             header("Location: index.php");
//     exit;
// }

// // Check if authorization code is present
// if (!isset($_GET['code'])) {
//                                     $msg = "Sometning went wrong !!!!!!";
//             $_SESSION['login_error'] = $msg; // optional: pass error via session
//             header("Location: index.php");
//     exit;
// }

// $code = $_GET['code'];
// // echo "Authorization Code: " . htmlspecialchars($code) . "<br>";

// // Prepare data to exchange authorization code for tokens
// $post_fields = [
//     'client_id' => $client_id,
//     'scope' => $scope,
//     'code' => $code,
//     'redirect_uri' => $redirect_uri,
//     'grant_type' => 'authorization_code',
//     'client_secret' => $client_secret,
// ];

// // Initialize cURL request
// $curl = curl_init($token_url);
// curl_setopt($curl, CURLOPT_POST, true);
// curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_fields));
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // Only for testing
// curl_setopt($curl, CURLOPT_VERBOSE, true); // Enable verbose output

// // Execute cURL and get response
// $response = curl_exec($curl);

// // Check for cURL errors
// if (curl_error($curl)) {
//                                 $msg = "Sometning went wrong !!!";
//             $_SESSION['login_error'] = $msg; // optional: pass error via session
//             header("Location: index.php");
//             exit;
// }

// $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// curl_close($curl);

// // Try to decode JSON response
// $token_data = json_decode($response, true);

// if (json_last_error() !== JSON_ERROR_NONE) {
//                                 $msg = "Sometning went wrong !!!";
//             $_SESSION['login_error'] = $msg; // optional: pass error via session
//             header("Location: index.php");
//             exit;
// }

// // echo "<h2>Decoded Token Response</h2>";
// // echo "<pre>" . htmlspecialchars(json_encode($token_data, JSON_PRETTY_PRINT)) . "</pre>";

// // Function to decode JWT token (basic decoding - not verifying signature)
// function decodeJWT($jwt) {
//     $parts = explode('.', $jwt);
//     if (count($parts) !== 3) {
//         return false;
//     }
//     $payload = base64_decode(strtr($parts[1], '-_', '+/'));
//     return json_decode($payload, true);
// }

// // Decode the ID token to get user info
// if (isset($token_data['id_token'])) {
//     $id_token = $token_data['id_token'];
//     $user_claims = decodeJWT($id_token);
    
//     if ($user_claims) {
//         // echo "<h2>User Info from ID Token</h2>";
//         // echo "Email: " . htmlspecialchars($user_claims['email'] ?? 'N/A') . "<br>";
//         // echo "Name: " . htmlspecialchars($user_claims['name'] ?? 'N/A') . "<br>";
//         // echo "Preferred Username: " . htmlspecialchars($user_claims['preferred_username'] ?? 'N/A') . "<br>";
//         // echo "User ID (OID): " . htmlspecialchars($user_claims['oid'] ?? 'N/A') . "<br>";



//         // Store in session
//         $_SESSION['user_email'] = $user_claims['email'] ?? '';
//         $_SESSION['user_name'] = $user_claims['name'] ?? '';
//         $_SESSION['user_id'] = $user_claims['oid'] ?? '';
//         $_SESSION['access_token'] = $token_data['access_token'];



//         // Fetch user from user_activity_management
//         if (isset($user_claims['email'])) {
//             $email = $user_claims['email'];

//             $stmt = $conn->prepare("SELECT * FROM user_activity_management WHERE email = ?");
//             $stmt->bind_param("s", $email);

//             if ($stmt->execute()) {
//                 $result = $stmt->get_result();

//                 if ($result->num_rows > 0) {
//                     // echo "<h3>User Found in user_activity_management Table</h3>";
//                     $user = $result->fetch_assoc();

//                     if(check_for_login('robi',$user['email'],$user['password'],1)){
                        
//         $_SESSION["user_type"] = "admin";
//         $_SESSION['mhafuz'] = 'Active';
//                                     $nonce = bin2hex(random_bytes(12)); // you can use your own nonce if already set
//             echo "<script nonce='$nonce'>window.top.location='../../../views/eProcurement_mod/eProcurement/eprocurement_entry.php';</script>";
//             exit;
//                   }
//                 } else {
       
//                                 $msg = "No user found !!!";
//             $_SESSION['login_error'] = $msg; // optional: pass error via session
//             header("Location: index.php");
//             exit;
//                 }

//                 $stmt->close();
//             } else {
//                                              $msg = "Something Went wrong!!  !!!";
//             $_SESSION['login_error'] = $msg; // optional: pass error via session
//             header("Location: index.php");
//              exit;
//             }
//         } else {
//                                           $msg = "Something Went wrong!!!";
//             $_SESSION['login_error'] = $msg; // optional: pass error via session
//             header("Location: index.php");
//              exit;
//         }
//     }
// }
?>
<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
session_start();
require 'config.php';
require_once "../../../controllers/routing/default_values.php";
require_once "../../../controllers/config/check_login.php";
require_once "../../../controllers/config/db_con_live_static.php";

// Function to show error modal and redirect
function showErrorModal($message) {
    echo '<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Error</title>
        <style>
            body {
                margin: 0;
                padding: 0;
                font-family: Arial, sans-serif;
                background-color: rgba(0, 0, 0, 0.5);
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
            }
            .modal {
                background: white;
                padding: 30px;
                border-radius: 10px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
                text-align: center;
                max-width: 400px;
                width: 90%;
                animation: fadeIn 0.3s ease-in;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: scale(0.8); }
                to { opacity: 1; transform: scale(1); }
            }
            .error-icon {
                color: #e74c3c;
                font-size: 48px;
                margin-bottom: 15px;
            }
            .error-title {
                color: #2c3e50;
                font-size: 24px;
                margin-bottom: 15px;
                font-weight: bold;
            }
            .error-message {
                color: #7f8c8d;
                font-size: 16px;
                margin-bottom: 20px;
                line-height: 1.5;
            }
            .countdown {
                color: #3498db;
                font-size: 14px;
                font-weight: bold;
            }
            .progress-bar {
                width: 100%;
                height: 4px;
                background-color: #ecf0f1;
                border-radius: 2px;
                margin-top: 15px;
                overflow: hidden;
            }
            .progress-fill {
                height: 100%;
                background-color: #3498db;
                width: 100%;
                animation: shrink 5s linear forwards;
            }
            @keyframes shrink {
                from { width: 100%; }
                to { width: 0%; }
            }
        </style>
    </head>
    <body>
        <div class="modal">
            <div class="error-icon">⚠️</div>
            <div class="error-title">Error</div>
            <div class="error-message">' . htmlspecialchars($message) . '</div>
            <div class="countdown">Redirecting in <span id="countdown">5</span> seconds...</div>
            <div class="progress-bar">
                <div class="progress-fill"></div>
            </div>
        </div>
        
        <script>
            let countdown = 5;
            const countdownElement = document.getElementById("countdown");
            
            const timer = setInterval(() => {
                countdown--;
                countdownElement.textContent = countdown;
                
                if (countdown <= 0) {
                    clearInterval(timer);
                    window.location.href = "index.php";
                }
            }, 1000);
        </script>
    </body>
    </html>';
    exit;
}

// Check if Azure AD returned an error
if (isset($_GET['error'])) {
    $msg = "Something went wrong with Azure AD authentication!";
    $_SESSION['login_error'] = $msg;
    showErrorModal($msg);
}

// Check if authorization code is present
if (!isset($_GET['code'])) {
    $msg = "No authorization code received!";
    $_SESSION['login_error'] = $msg;
    showErrorModal($msg);
}

$code = $_GET['code'];

// Prepare data to exchange authorization code for tokens
$post_fields = [
    'client_id' => $client_id,
    'scope' => $scope,
    'code' => $code,
    'redirect_uri' => $redirect_uri,
    'grant_type' => 'authorization_code',
    'client_secret' => $client_secret,
];

// Initialize cURL request
$curl = curl_init($token_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_fields));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // Only for testing
curl_setopt($curl, CURLOPT_VERBOSE, true); // Enable verbose output

// Execute cURL and get response
$response = curl_exec($curl);

// Check for cURL errors
if (curl_error($curl)) {
    $msg = "Connection error occurred during authentication!";
    $_SESSION['login_error'] = $msg;
    curl_close($curl);
    showErrorModal($msg);
}

$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);

// Try to decode JSON response
$token_data = json_decode($response, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    $msg = "Invalid response from authentication server!";
    $_SESSION['login_error'] = $msg;
    showErrorModal($msg);
}

// Function to decode JWT token (basic decoding - not verifying signature)
function decodeJWT($jwt) {
    $parts = explode('.', $jwt);
    if (count($parts) !== 3) {
        return false;
    }
    $payload = base64_decode(strtr($parts[1], '-_', '+/'));
    return json_decode($payload, true);
}

// Decode the ID token to get user info
if (isset($token_data['id_token'])) {
    $id_token = $token_data['id_token'];
    $user_claims = decodeJWT($id_token);

    if ($user_claims) {
        // Store in session
        $_SESSION['user_email'] = $user_claims['email'] ?? '';
        $_SESSION['user_name'] = $user_claims['name'] ?? '';
        $_SESSION['user_id'] = $user_claims['oid'] ?? '';
        $_SESSION['access_token'] = $token_data['access_token'];

        // Fetch user from user_activity_management
        if (isset($user_claims['email'])) {
            $email = $user_claims['email'];

            $stmt = $conn->prepare("SELECT * FROM user_activity_management WHERE email = ? ");
            $stmt->bind_param("s", $email);

            if ($stmt->execute()) {
                $result = $stmt->get_result();

                if ($result->num_rows > 0) {
                    $user = $result->fetch_assoc();

                    if(check_for_login('robi',$user['email'],$user['password'],1)){
                        $_SESSION["user_type"] = "admin";
                        $_SESSION['mhafuz'] = 'Active';
                        $nonce = bin2hex(random_bytes(12));
                        echo "<script nonce='$nonce'>window.top.location='../../../views/eProcurement_mod/eProcurement/eprocurement_entry.php';</script>";
                        exit;
                    }
                } else {      
                    $msg = "User not found in our system!";
                    $_SESSION['login_error'] = $msg;
                    showErrorModal($msg);
                }

                $stmt->close();
            } else {
                $msg = "Database connection error occurred!";
                $_SESSION['login_error'] = $msg;
                showErrorModal($msg);
            }
        } else {
            $msg = "Email not found in authentication response!";
            $_SESSION['login_error'] = $msg;
            showErrorModal($msg);
        }
    }
} else {
    $msg = "Authentication token is invalid!";
    $_SESSION['login_error'] = $msg;
    showErrorModal($msg);
}
?>
