<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Addressing PHPSESSID SameSite rejection
session_start();

require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');
require_once('../libs/classes/MyMethods.php');

if (!isset($_SESSION['userid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$crud = new App_DB(DBU::$dba_user);
$method = new MyMethods();

$action = $_REQUEST['action'] ?? '';

// Encryption setup
// Ideally this should be in .env, but for now we use a hardcoded key as fallback if not set.
// A real app should define ENCRYPTION_KEY in .env
define('ENCRYPTION_KEY', 'madrasa_email_secret_key_2026');
define('ENCRYPTION_METHOD', 'aes-256-cbc');

function encrypt_password($password)
{
    $iv_length = openssl_cipher_iv_length(ENCRYPTION_METHOD);
    $iv = openssl_random_pseudo_bytes($iv_length);
    $encrypted = openssl_encrypt($password, ENCRYPTION_METHOD, ENCRYPTION_KEY, 0, $iv);
    return base64_encode($iv . $encrypted);
}

function decrypt_password($encrypted_full)
{
    if (empty($encrypted_full))
        return '';
    $data = base64_decode($encrypted_full);
    $iv_length = openssl_cipher_iv_length(ENCRYPTION_METHOD);
    $iv = substr($data, 0, $iv_length);
    $encrypted = substr($data, $iv_length);
    return openssl_decrypt($encrypted, ENCRYPTION_METHOD, ENCRYPTION_KEY, 0, $iv);
}

$response = ['success' => false, 'message' => 'Invalid action'];

switch ($action) {
    case 'fetchAccounts':
        $sql = "SELECT id, smtp_host, smtp_port, email_user, email_from, reply_to, encryption, account_type FROM email_config ORDER BY account_type DESC, created_at ASC";
        $accounts = $crud->getRecordSet($sql);

        $gmail_accounts = [];
        $personal_account = null;

        foreach ($accounts as $acc) {
            if ($acc['account_type'] === 'gmail') {
                $gmail_accounts[] = $acc;
            } else {
                $personal_account = $acc;
            }
        }

        // Fetch default mailer type from config
        $config_sql = "SELECT default_mailer_type FROM config LIMIT 1";
        $config_data = $crud->getRecordSet($config_sql);
        $default_type = !empty($config_data) ? $config_data[0]['default_mailer_type'] : 'gmail';

        $response = [
            'success' => true,
            'gmail' => $gmail_accounts,
            'personal' => $personal_account,
            'default_mailer_type' => $default_type
        ];
        break;

    case 'saveAccount':
        $id = $_POST['id'] ?? null;
        $type = $_POST['account_type'] ?? 'personal';
        $host = $_POST['smtp_host'] ?? '';
        $port = $_POST['smtp_port'] ?? '';
        $user = $_POST['email_user'] ?? '';
        $pass = $_POST['email_pass'] ?? '';
        $from = $_POST['email_from'] ?? '';
        $reply = $_POST['reply_to'] ?? '';
        $encryption = $_POST['encryption'] ?? 'tls';

        if ($type === 'personal') {
            // Check if another personal account exists (excluding current id)
            $check_sql = "SELECT id FROM email_config WHERE account_type = 'personal'";
            if ($id)
                $check_sql .= " AND id != $id";
            $existing = $crud->getRecordSet($check_sql);
            if (!empty($existing)) {
                $response['message'] = 'صرف ایک ہی پرسنل اکاؤنٹ شامل کیا جا سکتا ہے۔';
                break;
            }
        }

        $data = [
            'smtp_host' => $host,
            'smtp_port' => $port,
            'email_user' => $user,
            'email_from' => $from,
            'reply_to' => $reply,
            'encryption' => $encryption,
            'account_type' => $type
        ];

        if (!empty($pass)) {
            $data['email_pass'] = encrypt_password($pass);
        }

        if ($id) {
            $update_sql = "UPDATE email_config SET ";
            $parts = [];
            foreach ($data as $k => $v)
                $parts[] = "$k = '$v'";
            $update_sql .= implode(', ', $parts) . " WHERE id = $id";
            $crud->dbQuery($update_sql);
            $response = ['success' => true, 'message' => 'اکاؤنٹ کامیابی سے اپ ڈیٹ ہو گیا۔'];
        } else {
            // New account
            if (empty($pass)) {
                $response['message'] = 'پاس ورڈ لازمی ہے۔';
                break;
            }
            $cols = implode(', ', array_keys($data));
            $vals = "'" . implode("', '", array_values($data)) . "'";
            $insert_sql = "INSERT INTO email_config ($cols) VALUES ($vals)";
            $crud->dbQuery($insert_sql);
            $response = ['success' => true, 'message' => 'اکاؤنٹ کامیابی سے شامل ہو گیا۔'];
        }
        break;

    case 'deleteAccount':
        $id = $_POST['id'] ?? null;
        if ($id) {
            $crud->dbQuery("DELETE FROM email_config WHERE id = $id");
            $response = ['success' => true, 'message' => 'اکاؤنٹ ختم کر دیا گیا۔'];
        }
        break;

    case 'setDefaultType':
        $type = $_POST['type'] ?? 'gmail';
        if (in_array($type, ['gmail', 'personal'])) {
            $crud->dbQuery("UPDATE config SET default_mailer_type = '$type' LIMIT 1");
            $response = ['success' => true, 'message' => 'ڈیفالٹ سیٹنگ اپ ڈیٹ ہو گئی۔'];
        }
        break;
}

echo json_encode($response);
