<?php
session_start();
require_once 'includes/auth_check.php';
require_once '../config/database.php';

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request method.";
    header("Location: manage_users.php");
    exit();
}

// Get the action type
$action = $_POST['action'] ?? '';
$user_id = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);

// Validate user ID
if (!$user_id) {
    $_SESSION['error_message'] = "Invalid user ID.";
    header("Location: manage_users.php");
    exit();
}

// Initialize database connection
$database = new Database();
$db = $database->getConnection();

// Function to send email with proper template
function sendEmailTemplate($to, $name, $subject, $templateData) {
    $bankName = defined('BANK_NAME') ? BANK_NAME : 'Our Banking Platform';
    $bankLogo = defined('BANK_LOGO_URL') ? BANK_LOGO_URL : 'https://online.firstnationalbankinc.com/logo.png';
    $bankColor = defined('BANK_PRIMARY_COLOR') ? BANK_PRIMARY_COLOR : '#0066cc';
    $currentYear = date('Y');
    
    // Extract template variables
    extract($templateData);
    
    $emailBody = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>$subject</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333333;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        .email-container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #ffffff;
            border: 1px solid #dddddd;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .email-header {
            background-color: $bankColor;
            padding: 20px;
            text-align: center;
        }
        .email-header img {
            max-width: 200px;
            height: auto;
        }
        .email-body {
            padding: 20px 30px;
        }
        .email-footer {
            background-color: #f8f8f8;
            padding: 15px;
            text-align: center;
            font-size: 12px;
            color: #666666;
            border-top: 1px solid #dddddd;
        }
        h1 {
            color: $bankColor;
            margin-top: 0;
        }
        .button {
            display: inline-block;
            background-color: $bankColor;
            color: white;
            text-decoration: none;
            padding: 10px 20px;
            border-radius: 4px;
            margin: 20px 0;
            font-weight: bold;
        }
        .alert-box {
            padding: 15px;
            margin: 20px 0;
            border-radius: 4px;
        }
        .alert-warning {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
            color: #856404;
        }
        .alert-danger {
            background-color: #f8d7da;
            border-left: 4px solid #dc3545;
            color: #721c24;
        }
        .alert-success {
            background-color: #d4edda;
            border-left: 4px solid #28a745;
            color: #155724;
        }
        .alert-info {
            background-color: #d1ecf1;
            border-left: 4px solid #17a2b8;
            color: #0c5460;
        }
        .credentials-box {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 4px;
            padding: 15px;
            margin: 20px 0;
        }
        .text-center {
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            <img src="$bankLogo" alt="$bankName Logo">
        </div>
        <div class="email-body">
            <h1>$title</h1>
            <p>Dear $name,</p>
            
            $content
            
            <p>If you have any questions or need assistance, please contact our support team.</p>
            
            <p>Best regards,<br>The $bankName Team</p>
        </div>
        <div class="email-footer">
            <p>This is an automated message. Please do not reply to this email.</p>
            <p>© $currentYear $bankName. All rights reserved.</p>
            <p>For security reasons, please ensure that you keep your account details confidential.</p>
        </div>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
HTML;
    
    // Set content-type header for sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    
    // Additional headers
    $fromName = defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : $bankName;
    $fromEmail = defined('MAIL_FROM_ADDRESS') ? MAIL_FROM_ADDRESS : 'noreply@yourdomain.com';
    $headers .= "From: $fromName <$fromEmail>" . "\r\n";
    
    // Log the email attempt
    error_log("Attempting to send email to: $to, Subject: $subject");
    
    // Save a copy of the email to a file for debugging
    $logDir = "../logs";
    if (!is_dir($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $emailLog = fopen("$logDir/email_" . time() . ".html", "w");
    if ($emailLog) {
        fwrite($emailLog, "To: $to\nSubject: $subject\nHeaders: $headers\n\n$emailBody");
        fclose($emailLog);
        error_log("Email content saved to log file");
    }
    
    // Try to send email
    try {
        $result = mail($to, $subject, $emailBody, $headers);
        error_log("Mail function result: " . ($result ? "Success" : "Failed"));
        return $result;
    } catch (Exception $e) {
        error_log("Email sending error: " . $e->getMessage());
        return false;
    }
}

// Process the action
try {
    switch ($action) {
        case 'adjust_balance':
            // Get form data
            $currency = $_POST['currency'] ?? '';
            $adjustment_type = $_POST['adjustment_type'] ?? '';
            $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
            $description = trim($_POST['description'] ?? '');
            
            // Validate inputs
            if (empty($currency)) throw new Exception("Currency is required.");
            if (!in_array($adjustment_type, ['credit', 'debit'])) throw new Exception("Invalid adjustment type.");
            if ($amount <= 0) throw new Exception("Amount must be greater than zero.");
            if (empty($description)) throw new Exception("Description is required.");
            
            // Begin transaction
            $db->beginTransaction();
            
            // Get user information
            $user_stmt = $db->prepare("SELECT first_name, last_name, email, account_number FROM users WHERE id = ?");
            $user_stmt->execute([$user_id]);
            $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user) throw new Exception("User not found.");
            
            // Check if balance record exists
            $check_stmt = $db->prepare("SELECT balance FROM account_balances WHERE user_id = ? AND currency = ?");
            $check_stmt->execute([$user_id, $currency]);
            $balance_record = $check_stmt->fetch(PDO::FETCH_ASSOC);
            
            $current_balance = $balance_record ? (float)$balance_record['balance'] : 0;
            $new_balance = ($adjustment_type === 'credit') ? $current_balance + $amount : $current_balance - $amount;
            
            // Prevent negative balance for debit
            if ($adjustment_type === 'debit' && $new_balance < 0) {
                throw new Exception("Insufficient funds. Current balance: $current_balance $currency");
            }
            
            if ($balance_record) {
                // Update existing balance
                $update_stmt = $db->prepare("UPDATE account_balances SET balance = ?, last_updated = NOW() WHERE user_id = ? AND currency = ?");
                $update_stmt->execute([$new_balance, $user_id, $currency]);
            } else {
                // Create new balance record
                $insert_stmt = $db->prepare("INSERT INTO account_balances (user_id, account_number, currency, balance, last_updated) VALUES (?, ?, ?, ?, NOW())");
                $insert_stmt->execute([$user_id, $user['account_number'], $currency, $new_balance]);
            }
            
            // Record the transaction
            $trans_stmt = $db->prepare("
                INSERT INTO transactions (user_id, type, amount, currency, description, reference, status, transaction_type, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, 'completed', 'adjustment', NOW())
            ");
            $reference = 'ADM' . time();
            $trans_stmt->execute([
                $user_id, 
                $adjustment_type, 
                $amount, 
                $currency, 
                "Admin Adjustment: $description", 
                $reference
            ]);
            
            // Commit the transaction
            $db->commit();
            
            // Send email notification
            $fullName = $user['first_name'] . ' ' . $user['last_name'];
            $formattedAmount = number_format($amount, ($currency === 'BTC' || $currency === 'ETH') ? 8 : 2);
            $formattedBalance = number_format($new_balance, ($currency === 'BTC' || $currency === 'ETH') ? 8 : 2);
            
            $emailSubject = ucfirst($adjustment_type) . " Transaction Notification";
            $emailData = [
                'title' => ucfirst($adjustment_type) . " Transaction Notification",
                'content' => "
                    <p>We are writing to inform you that a " . strtolower($adjustment_type) . " transaction has been processed on your account.</p>
                    
                    <div class='alert-box alert-" . ($adjustment_type === 'credit' ? 'success' : 'info') . "'>
                        <p><strong>Transaction Details:</strong></p>
                        <p>Amount: $currency $formattedAmount</p>
                        <p>Type: " . ucfirst($adjustment_type) . "</p>
                        <p>Reference: $reference</p>
                        <p>Description: $description</p>
                        <p>Current Balance: $currency $formattedBalance</p>
                    </div>
                "
            ];
            
            $emailSent = sendEmailTemplate($user['email'], $fullName, $emailSubject, $emailData);
            
            $_SESSION['success_message'] = "Balance adjusted successfully. " . 
                ($emailSent ? "Email notification sent." : "Email notification could not be sent.");
            
            break;
            
        case 'reset_password':
            // Get user email
            $user_email = filter_input(INPUT_POST, 'user_email', FILTER_VALIDATE_EMAIL);
            
            if (!$user_email) throw new Exception("Invalid email address.");
            
            // Get user information
            $user_stmt = $db->prepare("SELECT first_name, last_name FROM users WHERE id = ? AND email = ?");
            $user_stmt->execute([$user_id, $user_email]);
            $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user) throw new Exception("User not found or email doesn't match.");
            
            // Generate a new password
            $new_password = bin2hex(random_bytes(4)); // 8 characters
            
            // Hash the password
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            
            // Update the user's password
            $update_stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
            $update_stmt->execute([$hashed_password, $user_id]);
            
            // Send email with the new password
            $fullName = $user['first_name'] . ' ' . $user['last_name'];
            
            $emailSubject = "Your Password Has Been Reset";
            $emailData = [
                'title' => "Password Reset",
                'content' => "
                    <p>Your password has been reset by an administrator.</p>
                    
                    <div class='credentials-box'>
                        <p><strong>Your new temporary password is:</strong> $new_password</p>
                    </div>
                    
                    <p class='alert-box alert-warning'>
                        For security reasons, please log in and change this temporary password immediately.
                    </p>
                    
                    <div class='text-center'>
                        <a href='" . $_SERVER['HTTP_ORIGIN'] . "/login.php' class='button'>Log In Now</a>
                    </div>
                "
            ];
            
            $emailSent = sendEmailTemplate($user_email, $fullName, $emailSubject, $emailData);
            
            $_SESSION['success_message'] = "Password has been reset. " . 
                ($emailSent ? "New password sent to user's email." : "Email with new password could not be sent.");
            
            break;
            
        case 'suspend_user':
            // Get user information
            $user_stmt = $db->prepare("SELECT first_name, last_name, email FROM users WHERE id = ?");
            $user_stmt->execute([$user_id]);
            $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user) throw new Exception("User not found.");
            
            // Update user status
            $update_stmt = $db->prepare("UPDATE users SET status = 'suspended' WHERE id = ?");
            $update_stmt->execute([$user_id]);
            
            // Send email notification
            $fullName = $user['first_name'] . ' ' . $user['last_name'];
            
            $emailSubject = "Your Account Has Been Suspended";
            $emailData = [
                'title' => "Account Suspended",
                'content' => "
                    <div class='alert-box alert-warning'>
                        <p>We regret to inform you that your account has been temporarily suspended.</p>
                    </div>
                    
                    <p>If you believe this is an error or would like to discuss reactivating your account, please contact our support team.</p>
                "
            ];
            
            $emailSent = sendEmailTemplate($user['email'], $fullName, $emailSubject, $emailData);
            
            $_SESSION['success_message'] = "User has been suspended. " . 
                ($emailSent ? "Email notification sent." : "Email notification could not be sent.");
            
            break;
            
        case 'activate_user':
            // Get user information
            $user_stmt = $db->prepare("SELECT first_name, last_name, email FROM users WHERE id = ?");
            $user_stmt->execute([$user_id]);
            $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user) throw new Exception("User not found.");
            
            // Update user status
            $update_stmt = $db->prepare("UPDATE users SET status = 'active' WHERE id = ?");
            $update_stmt->execute([$user_id]);
            
            // Send email notification
            $fullName = $user['first_name'] . ' ' . $user['last_name'];
            
            $emailSubject = "Your Account Has Been Activated";
            $emailData = [
                'title' => "Account Activated",
                'content' => "
                    <div class='alert-box alert-success'>
                        <p>Good news! Your account has been activated and is now fully operational.</p>
                    </div>
                    
                    <p>You can now log in and access all features of your account.</p>
                    
                    <div class='text-center'>
                        <a href='" . $_SERVER['HTTP_ORIGIN'] . "/login.php' class='button'>Log In Now</a>
                    </div>
                "
            ];
            
            $emailSent = sendEmailTemplate($user['email'], $fullName, $emailSubject, $emailData);
            
            $_SESSION['success_message'] = "User has been activated. " . 
                ($emailSent ? "Email notification sent." : "Email notification could not be sent.");
            
            break;
            
        case 'delete_user':
            // Get user information before deletion
            $user_stmt = $db->prepare("SELECT first_name, last_name, email FROM users WHERE id = ?");
            $user_stmt->execute([$user_id]);
            $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user) throw new Exception("User not found.");
            
            // Begin transaction
            $db->beginTransaction();
            
            // Delete user's data from related tables
            $tables = [
                'account_balances',
                'transactions',
                'next_of_kin',
                'notifications',
                'login_attempts'
            ];
            
            foreach ($tables as $table) {
                try {
                    $stmt = $db->prepare("DELETE FROM $table WHERE user_id = ?");
                    $stmt->execute([$user_id]);
                } catch (PDOException $e) {
                    // Ignore errors if table doesn't exist
                    continue;
                }
            }
            
            // Finally delete the user
            $delete_stmt = $db->prepare("DELETE FROM users WHERE id = ?");
            $delete_stmt->execute([$user_id]);
            
            // Commit the transaction
            $db->commit();
            
            // Send email notification
            $fullName = $user['first_name'] . ' ' . $user['last_name'];
            
            $emailSubject = "Your Account Has Been Deleted";
            $emailData = [
                'title' => "Account Deleted",
                'content' => "
                    <div class='alert-box alert-danger'>
                        <p>We're writing to inform you that your account has been deleted from our system.</p>
                    </div>
                    
                    <p>All your personal data and account information have been removed from our database.</p>
                    
                    <p>If you believe this was done in error or have any questions, please contact our support team.</p>
                "
            ];
            
            $emailSent = sendEmailTemplate($user['email'], $fullName, $emailSubject, $emailData);
            
            $_SESSION['success_message'] = "User has been permanently deleted. " . 
                ($emailSent ? "Email notification sent." : "Email notification could not be sent.");
            
            // Redirect to manage users page since the user no longer exists
            header("Location: manage_users.php");
            exit();
            
        default:
            throw new Exception("Invalid action specified.");
    }
    
    // Redirect back to the user profile page
    header("Location: view_user.php?id=$user_id");
    exit();
    
} catch (Exception $e) {
    $_SESSION['error_message'] = "Error: " . $e->getMessage();
    
    // Redirect back to the user profile page
    header("Location: view_user.php?id=$user_id");
    exit();
}
?>
