<?php 
session_start(); 

// ১. লগইন এবং মাল্টি-টেন্যান্ট সেশন চেক
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || !isset($_SESSION['isp_id'])) {
    header("Location: login.php");
    exit;
}

// সেশন ভ্যারিয়েবল রিসিভ
$current_isp_id = $_SESSION['isp_id'];
$logged_in_name = $_SESSION['admin_name'] ?? 'Unknown Staff';

include 'config.php';
include 'routeros_api.class.php'; 
date_default_timezone_set('Asia/Dhaka'); 

// ২. ডাটাবেস থেকে বর্তমান আইএসপির নিজস্ব মাইক্রোটিক এবং SMS সেটিংস তুলে আনা
$settings_res = mysqli_query($conn, "SELECT * FROM isp_settings WHERE isp_id = '$current_isp_id' LIMIT 1");
$isp_settings = mysqli_fetch_assoc($settings_res);

if (!$isp_settings) {
    die("আপনার আইএসপি সেটিংস (Mikrotik/SMS) কনফিগার করা নেই। অনুগ্রহ করে অ্যাডমিন প্যানেল থেকে সেটিংস আপডেট করুন।");
}

// ৩. শুধুমাত্র বর্তমান আইএসপি-র নিজস্ব তৈরি করা এরিয়া লিস্ট কুয়েরি করা
$area_options = [];
$sql_areas = "SELECT id, area_name FROM area_list WHERE isp_id = '$current_isp_id' ORDER BY area_name ASC";
$res_areas = mysqli_query($conn, $sql_areas);
if ($res_areas) {
    while ($row_area = mysqli_fetch_assoc($res_areas)) {
        $area_options[] = $row_area;
    }
}

// ৪. নতুন যুক্ত করা অংশ: ডাটাবেস থেকে বর্তমান আইএসপির প্রোফাইল/প্যাকেজ এবং বিলের তালিকা তুলে আনা
$package_options = [];
$sql_packages = "SELECT id, package_name, price FROM packages WHERE isp_id = '$current_isp_id' ORDER BY price ASC";
$res_packages = mysqli_query($conn, $sql_packages);
if ($res_packages) {
    while ($row_pack = mysqli_fetch_assoc($res_packages)) {
        $package_options[] = $row_pack;
    }
}

if (isset($_POST['submit'])) {
    $c_id = mysqli_real_escape_string($conn, $_POST['customer_id']);
    $pass = mysqli_real_escape_string($conn, $_POST['password']); 
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    $nid = mysqli_real_escape_string($conn, $_POST['nid_no']);
    $area = mysqli_real_escape_string($conn, $_POST['area']);
    $address = mysqli_real_escape_string($conn, $_POST['address']);
    $bill = mysqli_real_escape_string($conn, $_POST['bill_amount']);
    $profile = mysqli_real_escape_string($conn, $_POST['profile']); 
    
    $current_date = date('Y-m-d');          
    $current_datetime = date('Y-m-d H:i:s'); 
    $expiry = date('Y-m-d', strtotime('+1 month')); 

    // গ্রাহক টেবিলে ইনসার্ট
    $sql = "INSERT INTO customers (isp_id, customer_id, password, name, phone, nid_no, area, address, bill_amount, package, expiry_date, connection_date, status) 
            VALUES ('$current_isp_id', '$c_id', '$pass', '$name', '$phone', '$nid', '$area', '$address', '$bill', '$profile', '$expiry', '$current_date', 'active')";
    
    if (mysqli_query($conn, $sql)) {
        
        // transactions টেবিলে রেকর্ড রাখা
        $tx_sql = "INSERT INTO transactions (isp_id, customer_id, amount, payment_method, trx_id, payment_date) 
                   VALUES ('$current_isp_id', '$c_id', '$bill', '$logged_in_name', 'new connection', '$current_datetime')";
        mysqli_query($conn, $tx_sql);

        // মাইক্রোটিক কানেকশন লজিক
        $m_ip   = $isp_settings['mikrotik_ip']; 
        $m_user = $isp_settings['mikrotik_user']; 
        $m_pass = $isp_settings['mikrotik_pass']; 
        $m_port = $isp_settings['mikrotik_port'];

        $api = new RouterosAPI();
        if ($api->connect($m_ip, $m_user, $m_pass, $m_port)) {
            $api->comm("/ppp/secret/add", array(
                "name" => $c_id, 
                "password" => $pass, 
                "profile" => $profile, 
                "service" => "pppoe"
            ));
            $api->disconnect();

            // SMS গেটওয়ে ও ব্র্যান্ডিং টেক্সট লজিক
            $api_key   = $isp_settings['sms_api_key'];
            $senderid  = $isp_settings['sms_sender_id'];
            $company_name = $isp_settings['company_name'] ?? 'Our ISP';
            $portal_url   = $isp_settings['portal_url'] ?? $_SERVER['HTTP_HOST'];
            $support_no   = $isp_settings['support_phone'] ?? '01XXXXXXXXX';

            $message = "Dear Customer\nWelcome to $company_name.\n\nUser Name: $name\nUser Portal: $portal_url\n\nLogin Details\nUser: $c_id\nPass: $pass\n\nService Contact:\n$support_no\n\nThanks For Using Our Internet Service.";
            
            if(!empty($api_key) && !empty($senderid)) {
                $encoded_msg = urlencode($message);
                $sms_url = "http://bulksmsbd.net/api/smsapi?api_key=$api_key&type=text&number=$phone&senderid=$senderid&message=$encoded_msg";
                @file_get_contents($sms_url); 
            }

            echo "<script>alert('Success! Client added, Transaction Recorded & SMS sent.'); window.location='index.php';</script>";
        } else { 
            echo "<script>alert('DB Saved & Transaction Recorded, but Mikrotik Connection Failed'); window.location='index.php';</script>";
        }
    } else {
        echo "Error: " . mysqli_error($conn);
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add New Client | SaaS ISP Portal</title>
    <style>
        body { 
            font-family: sans-serif; background: #f4f7f6; margin: 0; padding: 0; 
            width: 100%; min-height: 100vh; display: flex; flex-direction: column; 
        }
        .container {
            width: 100%; max-width: 100%; box-sizing: border-box; padding: 20px; 
            flex: 1; display: flex; justify-content: center; align-items: center;
        }
        .form-card { 
            background: white; padding: 30px; border-radius: 12px; 
            box-shadow: 0 4px 15px rgba(0,0,0,0.1); width: 100%; max-width: 800px; box-sizing: border-box; 
        }
        .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 15px; }
        .form-group { display: flex; flex-direction: column; }
        input, select { 
            width: 100%; padding: 12px; margin-bottom: 5px; border: 1px solid #ddd; 
            border-radius: 6px; box-sizing: border-box; font-size: 16px; background-color: #f9f9f9; 
        }
        label { font-size: 14px; color: #444; display: block; margin-bottom: 5px; font-weight: bold; }
        .button-group { margin-top: 20px; }
        button { 
            width: 100%; padding: 14px; background: #4f46e5; color: white; border: none; 
            border-radius: 6px; cursor: pointer; font-weight: bold; font-size: 16px; 
        }
        button:hover { background: #4338ca; }
        
        #loadingOverlay {
            display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(255, 255, 255, 0.9); z-index: 9999; flex-direction: column; justify-content: center; align-items: center;
        }
        .spinner {
            width: 40px; height: 40px; border: 4px solid #f3f3f3; border-top: 4px solid #4f46e5; border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        
        @media (max-width: 600px) {
            .form-card { padding: 15px; border-radius: 0px; }
            .container { padding: 0px; }
        }
    </style>
</head>
<body>

    <div id="loadingOverlay">
        <div class="spinner"></div>
        <p style="margin-top: 15px; font-family: sans-serif; color: #4f46e5;">সিস্টেম প্রসেস হচ্ছে, অপেক্ষা করুন...</p>
    </div>

    <div class="container">
        <div class="form-card">
            <h2 style="margin-top:0; text-align: center; font-size: 24px; color: #333;">Add New Client</h2>
            <div style="text-align: center; font-size: 14px; color: #666; margin-bottom: 25px;">Entry By: <b><?php echo htmlspecialchars($logged_in_name); ?></b></div>
            
            <form method="post" onsubmit="showLoading()">
                <div class="form-grid">
                    
                    <div class="form-group">
                        <label>Customer Username:</label>
                        <input type="text" name="customer_id" placeholder="Enter Username" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Mikrotik & Portal Password:</label>
                        <input type="text" name="password" placeholder="Enter Password" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Full Name:</label>
                        <input type="text" name="name" placeholder="Full Name" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Phone Number:</label>
                        <input type="number" name="phone" placeholder="Phone Number" required>
                    </div>
                    
                    <div class="form-group">
                        <label>NID Number:</label>
                        <input type="number" name="nid_no" placeholder="NID Number" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Select Area:</label>
                        <select name="area" required>
                            <option value="" disabled selected>Select Area</option>
                            <?php foreach ($area_options as $option): ?>
                                <option value="<?php echo htmlspecialchars($option['area_name']); ?>">
                                    <?php echo htmlspecialchars($option['area_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Full Address:</label>
                        <input type="text" name="address" placeholder="Full Address" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Choose Profile:</label>
                        <select name="profile" id="profile" onchange="updateBill()" required>
                            <option value="" disabled selected>Select Profile</option>
                            <?php foreach ($package_options as $pack): ?>
                                <option value="<?php echo htmlspecialchars($pack['package_name']); ?>" data-price="<?php echo $pack['price']; ?>">
                                    <?php echo htmlspecialchars($pack['package_name']) . " (" . $pack['price'] . " TK)"; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Monthly Bill (TK):</label>
                        <input type="number" name="bill_amount" id="bill_amount" placeholder="Price will auto-fill" readonly required>
                    </div>
                    
                </div> 
                <div class="button-group">
                    <button type="submit" name="submit">Save & Create in Mikrotik</button>
                    <a href="index.php" style="display:block; text-align:center; margin-top:15px; color:#999; text-decoration:none; font-size: 14px;">Cancel</a>
                </div>
            </form>
        </div>
    </div>

    <script>
        // প্রোফাইল সিলেক্ট করলে অটোমেটিকভাবে ডাটা-প্রাইস থেকে বিল বসে যাবে
        function updateBill() {
            var select = document.getElementById('profile');
            var billInput = document.getElementById('bill_amount');
            var selectedOption = select.options[select.selectedIndex];
            var price = selectedOption.getAttribute('data-price');
            if (price) { billInput.value = price; }
        }

        function showLoading() {
            document.getElementById('loadingOverlay').style.display = 'flex';
        }
    </script>
</body>
</html>