<?php
session_start();
ob_start();

$theme = json_decode(file_get_contents(__DIR__ . "/../../config/theme.json"), true);
if (!isset($theme) || !is_array($theme)) {
    die("Konfigurasi theme tidak ditemukan atau tidak valid.");
}

$access = json_decode(file_get_contents(__DIR__ . "/../../config/access.json"), true);
if (!isset($access) || !is_array($access)) {
    die("Konfigurasi access tidak ditemukan atau tidak valid.");
}

if (empty($_SESSION['login_exp']))
{
    header("Location: index?path=index.php");
    ob_end_flush();
    exit;
}

if (empty($_SESSION['access_token'])) 
{
    http_response_code(500);
    die('Access Denied');
}

if (isset($_SESSION['flash_message'])) {
    $flash = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}

$fileIP = "../../blacklist.txt";
$dataIPList = file_exists($fileIP) ? file_get_contents($fileIP) : '';

if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
    
    if($_POST['param'] == 'theme')
    {
        
        $jsonFilePath = __DIR__ . "/../../config/theme.json";

        if (!file_exists($jsonFilePath)) {
            die("Error: theme not found!");
        }
        
        if (empty($_SESSION['change_template'])) {
            if (!isset($_POST['template_select'], $_POST['bgImage_select'], $_POST['bgImage_change'])) {
                die("Error: Missing parameters!");
            }
    
            $_SESSION['template_select'] = $_POST['template_select'];
            $_SESSION['bgImage_select'] = $_POST['bgImage_select'];
            $_SESSION['bgImage_change'] = $_POST['bgImage_change'];
            $_SESSION['change_template'] = 'ok';
    
            session_write_close();
            header("Location: profile?path=need-pin-access");
            exit;
        }
        
        if (!isset($_POST['pin_access_web'])) {
            die("Error: PIN is required!");
        }
        
        if ($access['pin_access_web'] === $_POST['pin_access_web']) {
            unset($_SESSION['change_template']);
    
            $controlData = json_decode(file_get_contents($jsonFilePath), true);
    
            $updateData = [
                "template_select" => $_SESSION['template_select'],
                "bgImage_select" => $_SESSION['bgImage_select'],
                "bgImage_change" => $_SESSION['bgImage_change']
            ];
    
            foreach ($updateData as $key => $value) {
                if (isset($controlData[$key])) {
                    $controlData[$key] = $value;
                }
            }
    
            if (file_put_contents($jsonFilePath, json_encode($controlData, JSON_PRETTY_PRINT))) {
                $_SESSION['flash_message'] = [
                    'type' => 'success',
                    'message' => 'Template berhasil diperbarui!'
                ];
                session_write_close();
                header("Location: profile?path=success");
                exit;
            } else {
                $_SESSION['flash_message'] = [
                    'type' => 'danger',
                    'message' => 'Gagal memperbarui template!'
                ];
                session_write_close();
                header("Location: profile?path=failed");
                exit;
            }
        } else {
            $_SESSION['flash_message'] = [
                'type' => 'danger',
                'message' => 'Invalid PIN!'
            ];
            session_write_close();
            header("Location: profile?path=pin-wrong");
            exit;
        }
        
    } elseif($_POST['param'] == 'access') {
        $jsonFilePath = __DIR__ . "/../../config/access.json";

        if (!file_exists($jsonFilePath)) {
            die("Error: theme not found!");
        }
        
        if (empty($_SESSION['scam_set'])) {
            if (!isset($_POST['token_login'], $_POST['parameter'], $_POST['email_result'])) {
                die("Error: Missing parameters!");
            }
    
            $_SESSION['email_result'] = $_POST['email_result'];
            $_SESSION['parameter'] = $_POST['parameter'];
            $_SESSION['parameter_status'] = $_POST['parameter_status'];
            $_SESSION['token_login'] = $_POST['token_login'];
            $_SESSION['telegram_id'] = $_POST['telegram_id'];
            $_SESSION['telegram_secret_key'] = $_POST['telegram_secret_key'];
            $_SESSION['scam_set'] = 'ok';
    
            session_write_close();
            header("Location: profile?path=need-pin-access");
            exit;
        }
        
        if (!isset($_POST['pin_access_user'])) {
            die("Error: PIN is required!");
        }
        
        if ($access['pin_access_user'] === $_POST['pin_access_user']) {
            unset($_SESSION['scam_set']);
    
            $controlData = json_decode(file_get_contents($jsonFilePath), true);
    
            $updateData = [
                "email_result" => $_SESSION['email_result'],
                "parameter" => $_SESSION['parameter'],
                "parameter_status" => $_SESSION['parameter_status'],
                "token_login" => $_SESSION['token_login'],
                "telegram_id" => $_SESSION['telegram_id'],
                "telegram_secret_key" => $_SESSION['telegram_secret_key'],
            ];
    
            foreach ($updateData as $key => $value) {
                if (isset($controlData[$key])) {
                    $controlData[$key] = $value;
                }
            }
    
            if (file_put_contents($jsonFilePath, json_encode($controlData, JSON_PRETTY_PRINT))) {
                $_SESSION['flash_message'] = [
                    'type' => 'success',
                    'message' => 'Template berhasil diperbarui!'
                ];
                session_write_close();
                header("Location: profile?path=success");
                exit;
            } else {
                $_SESSION['flash_message'] = [
                    'type' => 'danger',
                    'message' => 'Gagal memperbarui template!'
                ];
                session_write_close();
                header("Location: profile?path=failed");
                exit;
            }
        } else {
            $_SESSION['flash_message'] = [
                'type' => 'danger',
                'message' => 'Invalid PIN!'
            ];
            session_write_close();
            header("Location: profile?path=pin-wrong");
            exit;
        }
    } else if($_POST['param'] == 'blacklist')
    {
        $dataIP = __DIR__ . "/../../blacklist.txt";
        
        file_put_contents($dataIP, $_POST['dblist'] . "\n");
        
        $_SESSION['flash_message'] = [
            'type' => 'success',
            'message' => 'Data has been updated'
        ];
        session_write_close();
        header("Location: profile?path=success");
        exit;
    } else if($_POST['param'] == 'saveresultwebshop')
    {

        function processWebshopLogsByDate($tanggalCari)
        {
            $theme = json_decode(file_get_contents(__DIR__ . "/../../config/theme.json"), true);
            if (!isset($theme) || !is_array($theme)) {
                die("Konfigurasi theme tidak ditemukan atau tidak valid.");
            }

            switch ($theme['template_select']) {
                case 'amz':
                    $baseDir = '/../../secure';
                    break;
                case 'irs':
                    $baseDir = '/../../secure-2';
                    break;
                case 'netflix':
                    $baseDir = '/../../secure-3';
                    break;
                case 'spectrum':
                    $baseDir = '/../../sspectrum';
                    break;
                case 'att':
                    $baseDir = '/../../DXNEbwZqcG';
                    break;
                case 'govUK':
                    $baseDir = '/../../MaIMTt67dp';
                    break;
                case 'xfinity':
                    $baseDir = '/../../hzvQTruKBa';
                    break;
                case 'apple':
                    $baseDir = '/../../zMEDH3rzcM';
                    break;
                case 'paypal':
                    $baseDir = '/../../U1IimACP7W';
                    break;
                case 'disney':
                    $baseDir = '/../../irjBhq6Esw';
                    break;
                default:
                    $_SESSION['flash_message'] = [
                        'type' => 'danger',
                        'message' => 'Template tidak dikenal!'
                    ];
                    session_write_close();
                    header("Location: profile?path=save-result");
                    exit;
            }
        
            $binFile = __DIR__ . $baseDir . '/logs/bin.txt';
            $dataLogFile = __DIR__ . $baseDir . '/logs/data_webshop_logs.txt';
            $resultFolder = __DIR__ . '/../../webshop_result/';
            $invalidLogFile = $resultFolder . 'invalid_lines.log';
        
            if (!is_dir($resultFolder)) {
                mkdir($resultFolder, 0777, true);
            }
        
            $targetIPs = [];

            $lines = file($binFile);
            foreach ($lines as $line) {
                if (strpos($line, $tanggalCari) !== false) {
                    $parts = explode('|', $line);
                    if (isset($parts[1])) {
                        $ip = trim($parts[1]);
                        $targetIPs[$ip] = true;
                    }
                }
            }
            
            
            $matches = [];
            $dataLines = file($dataLogFile);
            foreach ($dataLines as $line) {
                $parts = explode('|', $line);
                if (isset($parts[15])) {
                    $ipLog = trim($parts[15]);
                    if (isset($targetIPs[$ipLog])) {
                        $matches[] = $line;
                    }
                }
            }   
        
            if (!empty($matches)) {
                $resultFile = $resultFolder . $tanggalCari . '_result_webshop.txt';
                                $cleaned = array_map('trim', $matches);
                file_put_contents($resultFile, implode(PHP_EOL, $cleaned) . PHP_EOL, FILE_APPEND);
                $_SESSION['flash_message'] = [
                    'type' => 'success',
                    'message' => 'Result disimpan'
                ];
            } else {
                $_SESSION['flash_message'] = [
                    'type' => 'danger',
                    'message' => 'Tidak ada card'
                ];
            }
            
            if (!empty($invalidLines)) {
                file_put_contents($invalidLogFile, implode(PHP_EOL, $invalidLines) . PHP_EOL, FILE_APPEND);
            }
            
            session_write_close();
            header("Location: profile?path=save-result");
            exit;
        }
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $rawDate = $_POST['tanggal'];
            if (!empty($rawDate)) {
                $tanggalInput = date('m-d-Y', strtotime($rawDate));
                processWebshopLogsByDate($tanggalInput);
            } else {
                $_SESSION['flash_message'] = [
                    'type' => 'danger',
                    'message' =>  'Format tanggal tidak boleh kosong!'
                ];
                session_write_close();
                header("Location: profile?path=save-result");
                exit;
            }
        }
    }
    
} 

?>
<!-- This code generates the base URL for the website by combining the protocol, domain name, and directory path -->
<?php
    $rootFolder = basename($_SERVER['DOCUMENT_ROOT']);
    $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . str_replace('/pages', '', dirname($_SERVER['SCRIPT_NAME']));
?>
<!-- This code generates the base URL for the website by combining the protocol, domain name, and directory path -->

<!-- This code is useful for internal styles  -->
<?php ob_start(); ?>

        <!-- Prism CSS -->
        <link rel="stylesheet" href="<?php echo $baseUrl; ?>/assets/libs/prismjs/themes/prism-coy.min.css">

<?php $styles = ob_get_clean(); ?>
<!-- This code is useful for internal styles  -->

<!-- This code is useful for content -->
<?php ob_start(); ?>

            <!--APP-CONTENT START-->
            <div class="main-content app-content">
                <div class="container-fluid">

                    <!-- Start:: row-1 -->
                    <div class="row">
                        <div class="col-xl-12">
                            <?php if (!empty($flash)): ?>
                            <div class="alert alert-<?php echo htmlspecialchars($flash['type']); ?>">
                            <?php echo htmlspecialchars($flash['message']); ?>
                            </div>
                            <?php endif; ?>
                        <form method="post">
                        <div class="card custom-card">
                            <div class="top-left"></div>
                            <div class="top-right"></div>
                            <div class="bottom-left"></div>
                            <div class="bottom-right"></div>
                            <div class="card-header justify-content-between">
                                <div class="card-title">
                                    Web Config
                                </div>
                            </div>
                            <?php if(isset($_SESSION['change_template'])) : ?>
                            <div class="card-body">
                                <div class="row gy-4">
                                    

                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Pin Access</label>
                                        <input type="password" class="form-control" name="pin_access_web" />
                                    </div>
                                    <input type="hidden" name="param" value="theme" />

                                </div>
                            </div>
                            <?php else: ?>
                                <div class="card-body">
                                <div class="row gy-4">

                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Template Select</label>
                                        <select class="form-select" name="template_select">
                                            <option value="netflix" <?= ($theme['template_select'] == 'netflix') ? 'selected' : '' ?>>Netflix</option>
                                        </select>
                                    </div>
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Background Select</label>
                                        <select class="form-select" name="bgImage_select">
                                            <option value="money.png" <?= ($theme['bgImage_select'] == 'money.png') ? 'selected' : '' ?>>Background 1</option>
                                            <option value="money_2.png" <?= ($theme['bgImage_select'] == 'money_2.png') ? 'selected' : '' ?>>Background 2</option>
                                            <option value="background_img.png" <?= ($theme['bgImage_select'] == 'background_img.png') ? 'selected' : '' ?>>Background 3</option>
                                        </select>
                                    </div>
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Background Change</label>
                                        <select class="form-control" name="bgImage_change">
                                            <option value="0" <?= ($theme['bgImage_change'] == '0') ? 'selected' : '' ?>>Default</option>
                                            <option value="1" <?= ($theme['bgImage_change'] == '1') ? 'selected' : '' ?>>Switch</option>
                                        </select>
                                    </div>
                                    <input type="hidden" name="param" value="theme" />

                                </div>
                            </div>   
                            <?php endif; ?>
                            <button class="btn btn-primary">Save</button>
                        </div>
                        </form>
                        <form method="post">
                        <div class="card custom-card">
                            <div class="top-left"></div>
                            <div class="top-right"></div>
                            <div class="bottom-left"></div>
                            <div class="bottom-right"></div>
                            <div class="card-header justify-content-between">
                                <div class="card-title">
                                    Profile Settings
                                </div>
                            </div>
                            <?php if(isset($_SESSION['scam_set'])): ?>
                            <div class="card-body">
                                <div class="row gy-4">
                                    

                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Pin Access</label>
                                        <input type="password" class="form-control" name="pin_access_user" />
                                    </div>
                                    <input type="hidden" name="param" value="access" />

                                </div>
                            </div>
                            <?php else: ?>
                                <div class="card-body">
                                <div class="row gy-4">

                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Email Result</label>
                                        <input type="text" class="form-control" name="email_result" value="<?= $access['email_result']; ?>" />
                                    </div>
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Parameter Access</label>
                                        <input type="text" class="form-control" name="parameter" value="<?= $access['parameter']; ?>" />
                                    </div>
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Parameter Status</label>
                                        <select class="form-select" name="parameter_status">
                                            <option value="0" <?= ($access['parameter_status'] == '0') ? 'selected' : '' ?>>OFF</option>
                                            <option value="1" <?= ($access['parameter_status'] == '1') ? 'selected' : '' ?>>ON</option>
                                        </select>
                                    </div>
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Token Access</label>
                                        <input type="text" class="form-control" name="token_login" value="<?= $access['token_login']; ?>" />
                                    </div>
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Telegram ID</label>
                                        <input type="text" class="form-control" name="telegram_id" value="<?= $access['telegram_id']; ?>" />
                                    </div>
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label class="form-label">Telegram Secret</label>
                                        <input type="text" class="form-control" name="telegram_secret_key" value="<?= $access['telegram_secret_key']; ?>" />
                                    </div>
                                    <input type="hidden" name="param" value="access" />

                                </div>
                            </div>   
                            <?php endif; ?>
                            <button class="btn btn-primary">Save</button>
                        </div>
                        </form>
                        <form method="POST">
                        <div class="card custom-card">
                            <div class="top-left"></div>
                            <div class="top-right"></div>
                            <div class="bottom-left"></div>
                            <div class="bottom-right"></div>
                            <div class="card-header justify-content-between">
                                <div class="card-title">
                                    Save Result Webshop
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="row gy-4">
                                    
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label for="dblist" class="form-label">Select Date</label>
                                        <input class="form-control" type="date" id="dblist" name="tanggal">
                                    </div>
                                    <input type="hidden" name="param" value="saveresultwebshop" />

                                </div>
                            </div>
                            <button class="btn btn-primary">Save</button>
                        </div>
                        </form>
                        <form method="POST">
                        <div class="card custom-card">
                            <div class="top-left"></div>
                            <div class="top-right"></div>
                            <div class="bottom-left"></div>
                            <div class="bottom-right"></div>
                            <div class="card-header justify-content-between">
                                <div class="card-title">
                                    IP BlackList
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="row gy-4">
                                    
                                    <div class="col-xl-6 col-lg-6 col-md-6 col-sm-12">
                                        <label for="dblist" class="form-label">List IP</label>
                                        <textarea class="form-control" id="dblist" name="dblist" rows="5"><?= htmlspecialchars($dataIPList) ?></textarea>
                                    </div>
                                    <input type="hidden" name="param" value="blacklist" />

                                </div>
                            </div>
                            <button class="btn btn-primary">Save</button>
                        </div>
                        </form>
                    </div>
                </div>
            </div>
            <!--APP-CONTENT CLOSE-->
            
<?php $content = ob_get_clean(); ?>
<!-- This code is useful for content -->

<!-- This code is useful for internal scripts  -->
<?php ob_start(); ?>

        <!-- Prism JS -->
        <script src="<?php echo $baseUrl; ?>/assets/libs/prismjs/prism.js"></script>
        <script src="<?php echo $baseUrl; ?>/assets/js/prism-custom.js"></script>
        
<?php $scripts = ob_get_clean(); ?>
<!-- This code is useful for internal scripts  -->

<!-- This code use for render base file -->
<?php include 'layouts/base.php'; ?>
<!-- This code use for render base file -->