<?php
$servername = "localhost";
$username = "otatacom_daniel";
$password = "@#Wanji9891";
$dbname = "otatacom_renti";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Assume these variables are provided by a form or other input mechanism
$agent_id = $_POST['agent']; // Agent ID
$old_password = $_POST['oldpin'];
$new_password = $_POST['newpin']; // New password

// Check if the agent exists and fetch the current hashed password
$sql = "SELECT password FROM agents WHERE code = ?";
$stmt = $conn->prepare($sql);

if ($stmt === false) {
    die("Prepare failed: " . $conn->error);
}

$stmt->bind_param('i', $agent_id);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    $stmt->bind_result($current_hashed_password);
    $stmt->fetch();
    
    // Verify the old password
    if (password_verify($old_password, $current_hashed_password)) {
        // Hash the new password
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        
        // Prepare the SQL statement for updating the password
        $sql = "UPDATE agents SET password = ? WHERE code = ?";
        $stmt = $conn->prepare($sql);
        
        if ($stmt === false) {
            die("Prepare failed: " . $conn->error);
        }

        // Bind the parameters
        $stmt->bind_param('si', $hashed_password, $agent_id);

        // Execute the statement
        if ($stmt->execute() === false) {
            die("Execute failed: " . $stmt->error);
        } else {
            echo "<script type='text/javascript'>
              window.location.href='https://bluespacegrouplimited.com/renti/updateData.php?wakala_number=$agent_id&newpin=$new_password';
            </script>";
        }

        // Close the statement
        $stmt->close();
    } else {
        echo "Old password is incorrect.";
    }
} else {
    echo "Agent not found.";
    echo $agent_id;
}

// Close the connection
$conn->close();
?>
