<?php
// Prevent direct access
if (!defined('LUNA_APP')) {
    define('LUNA_APP', true);
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/messages.php';
require_once __DIR__ . '/../modules/zalo/service.php';

$messages = load_messages();

// Check if this is an AJAX request
$isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'fetch';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $license = $_POST['license'] ?? '';
    
    // Verify license
    $dbSettings = db_connection_settings();
    if ($license !== ($dbSettings['license'] ?? '')) {
        $errorMsg = 'Invalid license';
        
        // Set flash message for both AJAX and regular requests
        $_SESSION['flash']['error'] = $errorMsg;
        
        if ($isAjax) {
            header('Content-Type: application/json');
            echo json_encode(['ok' => false, 'message' => $errorMsg]);
            exit;
        } else {
            header('Location: ../index.php?zalo&error=' . urlencode($errorMsg));
            exit;
        }
    }
    
    try {
        switch ($action) {
            case 'create':
                createZalo($isAjax);
                break;
            case 'update':
                updateZalo($isAjax);
                break;
            case 'delete':
                deleteZalo($isAjax);
                break;
            default:
                throw new Exception('Invalid action');
        }
    } catch (Exception $e) {
        $errorMsg = $e->getMessage();
        
        // Set flash message for both AJAX and regular requests
        $_SESSION['flash']['error'] = $errorMsg;
        
        if ($isAjax) {
            header('Content-Type: application/json');
            echo json_encode(['ok' => false, 'message' => $errorMsg]);
            exit;
        } else {
            header('Location: ../index.php?zalo&error=' . urlencode($errorMsg));
            exit;
        }
    }
}

/**
 * Create new Zalo config
 */
function createZalo($isAjax = false) {
    global $messages;
    
    $name = trim($_POST['name'] ?? '');
    $userNumber = (int)($_POST['user_number'] ?? 0);
    $messageNumber = (int)($_POST['message_number'] ?? 0);
    $token = trim($_POST['token'] ?? '');
    $linkQR = trim($_POST['link_qr'] ?? '');
    $qrImagePath = trim($_POST['qr_image_path'] ?? '');
    
    // Validate required fields
    if (empty($name)) {
        throw new Exception($messages['zalo_error_name_required'] ?? 'Tên Bot không được để trống');
    }
    
    if (empty($token)) {
        throw new Exception($messages['zalo_error_token_required'] ?? 'Token không được để trống');
    }
    
    // If image uploaded (base64), save it and use that path instead
    if (!empty($qrImagePath) && strpos($qrImagePath, 'data:image') === 0) {
        $linkQR = saveQRImage($qrImagePath, $name);
    }
    
    if (empty($linkQR)) {
        throw new Exception($messages['zalo_error_qr_required'] ?? 'Vui lòng upload QR Code');
    }
    
    $conn = db_connect();
    
    // Check if table exists, create if not
    $checkTable = "IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Zalo')
                   CREATE TABLE Zalo (
                       Id INT PRIMARY KEY IDENTITY(1,1),
                       Name NVARCHAR(500) NOT NULL,
                       User_Number SMALLINT NOT NULL,
                       Message_Number SMALLINT NOT NULL,
                       Token NVARCHAR(500) NOT NULL,
                       Link_QR NVARCHAR(500) NOT NULL
                   )";
    sqlsrv_query($conn, $checkTable);
    
    // Check if token already exists
    $checkTokenSql = "SELECT COUNT(*) as count FROM Zalo WHERE Token = ?";
    $checkStmt = sqlsrv_query($conn, $checkTokenSql, [$token]);
    if ($checkStmt) {
        $row = sqlsrv_fetch_array($checkStmt, SQLSRV_FETCH_ASSOC);
        if ($row && $row['count'] > 0) {
            sqlsrv_free_stmt($checkStmt);
            db_disconnect($conn);
            throw new Exception($messages['zalo_error_token_duplicate'] ?? 'Token này đã tồn tại trong hệ thống');
        }
        sqlsrv_free_stmt($checkStmt);
    }
    
    // Insert new record with OUTPUT to get the new ID
    $sql = "INSERT INTO Zalo (Name, User_Number, Message_Number, Token, Link_QR) 
            OUTPUT INSERTED.Id
            VALUES (?, ?, ?, ?, ?)";
    $params = [$name, $userNumber, $messageNumber, $token, $linkQR];
    
    $stmt = sqlsrv_query($conn, $sql, $params);
    
    if (!$stmt) {
        $errors = sqlsrv_errors();
        db_disconnect($conn);
        throw new Exception('Database error: ' . print_r($errors, true));
    }
    
    // Get the newly inserted ID
    $newId = null;
    if (sqlsrv_fetch($stmt)) {
        $newId = (int)sqlsrv_get_field($stmt, 0);
    }
    
    sqlsrv_free_stmt($stmt);
    
    // Rename QR file to {ID}.jpg if it was uploaded
    if ($newId && !empty($linkQR)) {
        $oldFilePath = __DIR__ . '/../' . $linkQR;
        $uploadDir = __DIR__ . '/../data/qr_codes/';
        
        // Ensure upload directory exists
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        if (file_exists($oldFilePath)) {
            $newFileName = $newId . '.jpg';
            $newFilePath = $uploadDir . $newFileName;
            $newRelativePath = 'data/qr_codes/' . $newFileName;
            
            // Rename the file
            if (rename($oldFilePath, $newFilePath)) {
                // Update the Link_QR in database with new filename
                $updateSql = "UPDATE Zalo SET Link_QR = ? WHERE Id = ?";
                $updateStmt = sqlsrv_query($conn, $updateSql, [$newRelativePath, $newId]);
                if ($updateStmt) {
                    sqlsrv_free_stmt($updateStmt);
                }
            }
        }
    }
    
    db_disconnect($conn);
    
    $successMsg = $messages['zalo_success_created'] ?? 'Thêm mới Zalo config thành công!';
    
    // Set flash message for both AJAX and regular requests
    $_SESSION['flash']['success'] = $successMsg;
    
    if ($isAjax) {
        header('Content-Type: application/json');
        echo json_encode(['ok' => true, 'message' => $successMsg]);
        exit;
    } else {
        header('Location: ../index.php?zalo&success=' . urlencode($successMsg));
        exit;
    }
}

/**
 * Update Zalo config
 */
function updateZalo($isAjax = false) {
    global $messages;
    
    $id = (int)($_POST['id_zalo'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $userNumber = (int)($_POST['user_number'] ?? 0);
    $messageNumber = (int)($_POST['message_number'] ?? 0);
    $token = trim($_POST['token'] ?? '');
    $linkQR = trim($_POST['link_qr'] ?? '');
    $qrImagePath = trim($_POST['qr_image_path'] ?? '');
    
    if ($id <= 0) {
        throw new Exception('Invalid ID');
    }
    
    // Validate required fields
    if (empty($name)) {
        throw new Exception($messages['zalo_error_name_required'] ?? 'Tên Bot không được để trống');
    }
    
    if (empty($token)) {
        throw new Exception($messages['zalo_error_token_required'] ?? 'Token không được để trống');
    }
    if (empty($linkQR)) {
        throw new Exception($messages['zalo_error_linkQR_required'] ?? 'Chưa cập nhật QR cho BOT');
    } else {
        // Kiểm tra file QR có tồn tại không (chỉ check nếu không phải base64 image)
        if (strpos($linkQR, 'data:image') !== 0) {
            // Xây dựng đường dẫn tuyệt đối
            $qrFilePath = __DIR__ . '/../' . ltrim($linkQR, '/');
            
            // Kiểm tra file có tồn tại không
            if (!file_exists($qrFilePath)) {
                throw new Exception($messages['zalo_error_qr_file_not_found'] ?? 'File ảnh QR không tồn tại: ' . $linkQR);
            }
        }
    }
    $conn = db_connect();
    
    // Get old QR path if exists
    $oldQRPath = '';
    $getOldQRSql = "SELECT Link_QR FROM Zalo WHERE Id = ?";
    $getOldQRStmt = sqlsrv_query($conn, $getOldQRSql, [$id]);
    if ($getOldQRStmt) {
        $row = sqlsrv_fetch_array($getOldQRStmt, SQLSRV_FETCH_ASSOC);
        if ($row) {
            $oldQRPath = $row['Link_QR'];
        }
        sqlsrv_free_stmt($getOldQRStmt);
    }
    
    // If image uploaded (base64), save it and use that path instead
    if (!empty($qrImagePath) && strpos($qrImagePath, 'data:image') === 0) {
        // Save with temporary name first
        $linkQR = saveQRImage($qrImagePath, $name);
        
        // Rename to {ID}.jpg
        if (!empty($linkQR) && file_exists(__DIR__ . '/../' . $linkQR)) {
            $oldFilePath = __DIR__ . '/../' . $linkQR;
            $uploadDir = __DIR__ . '/../data/qr_codes/';
            $newFileName = $id . '.jpg';
            $newFilePath = $uploadDir . $newFileName;
            $newRelativePath = 'data/qr_codes/' . $newFileName;
            
            // Delete old QR file if exists and is different
            if (!empty($oldQRPath) && $oldQRPath !== $newRelativePath) {
                $oldFullPath = __DIR__ . '/../' . $oldQRPath;
                if (file_exists($oldFullPath)) {
                    @unlink($oldFullPath);
                }
            }
            
            // If target file already exists, delete it first
            if (file_exists($newFilePath)) {
                @unlink($newFilePath);
            }
            
            // Rename to final name
            if (rename($oldFilePath, $newFilePath)) {
                $linkQR = $newRelativePath;
            }
        }
    }
    
    // Check if token already exists (exclude current record)
    $checkTokenSql = "SELECT COUNT(*) as count FROM Zalo WHERE Token = ? AND Id != ?";
    $checkStmt = sqlsrv_query($conn, $checkTokenSql, [$token, $id]);
    if ($checkStmt) {
        $row = sqlsrv_fetch_array($checkStmt, SQLSRV_FETCH_ASSOC);
        if ($row && $row['count'] > 0) {
            sqlsrv_free_stmt($checkStmt);
            db_disconnect($conn);
            throw new Exception($messages['zalo_error_token_duplicate'] ?? 'Token này đã tồn tại trong hệ thống');
        }
        sqlsrv_free_stmt($checkStmt);
    }
    
    $sql = "UPDATE Zalo 
            SET Name = ?, User_Number = ?, Message_Number = ?, Token = ?, Link_QR = ?
            WHERE Id = ?";
    $params = [$name, $userNumber, $messageNumber, $token, $linkQR, $id];
    
    $stmt = sqlsrv_query($conn, $sql, $params);
    
    if (!$stmt) {
        $errors = sqlsrv_errors();
        db_disconnect($conn);
        throw new Exception('Database error: ' . print_r($errors, true));
    }
    
    sqlsrv_free_stmt($stmt);
    db_disconnect($conn);
    
    $successMsg = $messages['zalo_success_updated'] ?? 'Cập nhật Zalo config thành công!';
    
    // Set flash message for both AJAX and regular requests
    $_SESSION['flash']['success'] = $successMsg;
    
    if ($isAjax) {
        header('Content-Type: application/json');
        echo json_encode(['ok' => true, 'message' => $successMsg]);
        exit;
    } else {
        header('Location: ../index.php?zalo&success=' . urlencode($successMsg));
        exit;
    }
}

/**
 * Delete Zalo config
 */
function deleteZalo($isAjax = false) {
    global $messages;
    
    $id = (int)($_POST['id_zalo'] ?? 0);
    
    if ($id <= 0) {
        throw new Exception('Invalid ID');
    }
    
    $conn = db_connect();
    
    // Get QR path before deleting
    $qrPath = '';
    $getQRSql = "SELECT Link_QR FROM Zalo WHERE Id = ?";
    $getQRStmt = sqlsrv_query($conn, $getQRSql, [$id]);
    if ($getQRStmt) {
        $row = sqlsrv_fetch_array($getQRStmt, SQLSRV_FETCH_ASSOC);
        if ($row) {
            $qrPath = $row['Link_QR'];
        }
        sqlsrv_free_stmt($getQRStmt);
    }
    
    // Delete from database
    $sql = "DELETE FROM Zalo WHERE Id = ?";
    $stmt = sqlsrv_query($conn, $sql, [$id]);
    
    if (!$stmt) {
        $errors = sqlsrv_errors();
        db_disconnect($conn);
        throw new Exception('Database error: ' . print_r($errors, true));
    }
    
    sqlsrv_free_stmt($stmt);
    db_disconnect($conn);
    
    // Delete QR file if exists
    if (!empty($qrPath)) {
        $fullPath = __DIR__ . '/../' . $qrPath;
        if (file_exists($fullPath)) {
            @unlink($fullPath);
        }
    }
    
    $successMsg = $messages['zalo_success_deleted'] ?? 'Xóa Zalo config thành công!';
    
    // Set flash message for both AJAX and regular requests
    $_SESSION['flash']['success'] = $successMsg;
    
    if ($isAjax) {
        header('Content-Type: application/json');
        echo json_encode(['ok' => true, 'message' => $successMsg]);
        exit;
    } else {
        header('Location: ../index.php?zalo&success=' . urlencode($successMsg));
        exit;
    }
}

/**
 * Get all Zalo configs
 */
function zalo_list() {
    try {
        $conn = db_connect();
        
        // Get Zalo bots with actual user count from DataWork table
        $sql = "SELECT               
                    z.Id, 
                    z.Name, 
                    z.Message_Number, 
                    z.User_Max, 
                    z.Message_Max, 
                    z.Token, 
                    z.Link_QR,
                    (SELECT COUNT(*) 
                     FROM DataWork d2 
                     WHERE z.Id  = d2.Zalo_Id_Bot 
                          AND (
                          d2.So_QDNV = '' 
                          OR d2.So_QDNV = 'NULL' 
                          OR d2.So_QDNV IS NULL 
                          OR (
								d2.So_QDNV IS NOT NULL						
								AND d2.Ngayketthuc > GETDATE()  
              ))
                    ) as actual_user_count
                FROM Zalo z
                ORDER BY z.Id DESC";
        
        $stmt = sqlsrv_query($conn, $sql);
        $result = [];
        
        if ($stmt) {
            while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
                $result[] = [
                    'id' => $row['Id'],
                    'name' => $row['Name'],
                    'user_number' => $row['actual_user_count'], // Use actual count from DataWork
                    'message_number' => $row['Message_Number'],
                    'user_max' => $row['User_Max'],
                    'message_max' => $row['Message_Max'],
                    'token' => $row['Token'],
                    'link_qr' => $row['Link_QR']
                ];
            }
            sqlsrv_free_stmt($stmt);
        }
        
        db_disconnect($conn);
        return $result;
    } catch (Exception $e) {
        return [];
    }
}

/**
 * Save QR Image from base64
 */
function saveQRImage($base64Data, $configName) {
    // Create upload directory if not exists
    $uploadDir = __DIR__ . '/../data/qr_codes/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // Extract image data
    list($type, $data) = explode(';', $base64Data);
    list(, $data) = explode(',', $data);
    $data = base64_decode($data);
    
    // Get image extension
    $extension = 'png';
    if (strpos($type, 'jpeg') !== false || strpos($type, 'jpg') !== false) {
        $extension = 'jpg';
    } elseif (strpos($type, 'gif') !== false) {
        $extension = 'gif';
    } elseif (strpos($type, 'webp') !== false) {
        $extension = 'webp';
    }
    
    // Generate unique filename
    $filename = 'qr_' . preg_replace('/[^a-z0-9_-]/i', '_', $configName) . '_' . time() . '.' . $extension;
    $filePath = $uploadDir . $filename;
    
    // Save file
    if (file_put_contents($filePath, $data)) {
        // Return relative path
        return 'data/qr_codes/' . $filename;
    }
    
    return '';
}

