<?php
if(!defined('BASEPATH')) {
   die('Direct access to the script is not allowed');
}

$title = "Child Panels"; 

if ($settings["childpanel_selling"] == 1){
    header("Location:" . site_url());
    exit;
}
if( $settings["email_confirmation"] == 1  && $user["email_type"] == 1  ){
    header("Location:".site_url('confirm_email'));
    exit;
}
if( !isset($_SESSION["msmbilisim_userlogin"]) || $_SESSION["msmbilisim_userlogin"] != 1  || $user["client_type"] == 1  ){
    header("Location:".site_url('logout'));
    exit;
}

$client_id = $user['client_id']; 

// ADVANCED FIX: History ko Twig tak pahunchane ke liye data array me dala gaya hai
$panel_logs = $conn->prepare("SELECT * FROM childpanels WHERE client_id=:client_id ORDER BY id DESC");
$panel_logs->execute(array("client_id" => $client_id));
$_SESSION["data"]["panel_logs"] = $panel_logs->fetchAll(PDO::FETCH_ASSOC);

$currencies_file = $_SERVER["DOCUMENT_ROOT"]."/currencies.json";
$currencies_array = [];
if(file_exists($currencies_file)) {
    $currencies_array = json_decode(file_get_contents($currencies_file), 1);
}

$choose_currencies = ""; 
if (is_array($currencies_array)) {
    foreach($currencies_array as $code => $value){
        $choose_currencies .= '<option value="'.$code.'">'.$value["name"].' ('.$code.')</option>';
    }
}

$childpanel_nameservers = json_decode($settings["child_panel_nameservers"] ?? '{}', true);

if( $_POST ):
    if(isset($_POST["renew"]) && $_POST["renew"]){
        $renew_id = htmlspecialchars($_POST["renew_id"] ?? '');
        $childorders = $conn->prepare("SELECT * FROM childpanels WHERE id=:id AND client_id=:client_id");
        $childorders->execute(array("id" => $renew_id, "client_id" => $user["client_id"]));
        $childorders = $childorders->fetch(PDO::FETCH_ASSOC);

        if($childorders){
            $renew_months = 1; // Default renewal for 1 month
            $price = $settings["childpanel_price"] * $renew_months;

            if($user['balance'] < $price){
                $conn->beginTransaction();
                $update = $conn->prepare("UPDATE childpanels SET child_panel_status=:status WHERE id=:id");
                $update->execute(array("id"=>$childorders['id'], "status"=>"Suspended"));
                $conn->commit();
                $error    = 1;
                $errorText= $languageArray["error.neworder.balance.notenough"] ?? "Not enough balance";
            } else {
                $current_expiry = new DateTime($childorders['renewal_date']);
                $now = new DateTime("now");
                if ($current_expiry < $now) { $current_expiry = $now; }
                
                $current_expiry->modify('+' . $renew_months . ' month');
                $renewal_date = $current_expiry->format('Y-m-d');
                
                $conn->beginTransaction();
                $insert = $conn->prepare("UPDATE childpanels SET renewal_date=:renewal_date, child_panel_status=:status WHERE id=:id");
                $insert->execute(array("renewal_date"=>$renewal_date, "status"=>"Active", "id"=>$renew_id));
                    
                $update = $conn->prepare("UPDATE clients SET balance=:balance, spent=:spent WHERE client_id=:id");
                $update->execute(array("balance"=>$user["balance"]-$price, "spent"=>$user["spent"]+$price, "id"=>$user["client_id"]));
                
                $insert2 = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
                $insert2->execute(array("c_id"=>$user["client_id"], "action"=>"Child Panel Renewed with id : ".$renew_id." for ".$renew_months." month.", "ip"=>GetIP(), "date"=>date("Y-m-d H:i:s") ));
                
                if ( $insert && $update && $insert2 ):
                    $conn->commit();
                    $order_data = ['success'=>2,'id'=>$renew_id,"service"=>"Child Panel Renewal","link"=>$childorders["domain"],"quantity"=>$renew_months,"price"=>$price,"balance"=>$user["balance"] ];
                    $_SESSION["data"]["services"]   = "Child Panel";
                    $_SESSION["data"]["categories"] = "Child Panels";
                    $_SESSION["data"]["childpanel"] = $order_data;
                    header("Location:".site_url("child-panels"));
                    exit;
                else:
                    $conn->rollBack();
                    header("Location:".site_url("child-panels"));
                    exit;
                endif;
            }
        }
    }else{
        foreach ($_POST as $key => $value) { $_SESSION["data"][$key]  = $value; }
        
        $ip       = GetIP();
        $domain   = strip_tags(htmlspecialchars($_POST["panel_domain"] ?? ''));
        $currency = strip_tags(htmlspecialchars($_POST["panel_currency"] ?? ''));
        $username = strip_tags(htmlspecialchars($_POST["admin_username"] ?? ''));
        $password = strip_tags($_POST["admin_password"] ?? '');
        $re_password = strip_tags($_POST["admin_confirm_password"] ?? '');
        
        // NEW FEATURE: Get duration months from user form
        $duration_months = isset($_POST["panel_months"]) ? (int)$_POST["panel_months"] : 1;
        if($duration_months < 1) $duration_months = 1;
        
        $price = ($settings["childpanel_price"] ?? 0) * $duration_months;
        
        $date = new DateTime("now"); 
        $date->modify('+' . $duration_months . ' month');
        $renewal_date = $date->format('Y-m-d');
            
        if(empty($domain)): $error = 1; $errorText= "Please enter a valid domain name";
        elseif( empty($currency)): $error = 1; $errorText= "Please choose a valid currency";
        elseif( empty($username)): $error = 1; $errorText= "Enter a valid username";
        elseif( empty($password) ): $error = 1; $errorText= "Enter a valid Password";
        elseif( $password != $re_password ): $error = 1; $errorText= "Passwords do not match";  
        elseif( ( $price > $user["balance"] ) && ($user["balance_type"] == 2) ): $error = 1; $errorText= "Not enough balance";
        elseif( ( $user["balance"] - $price < "-".$user["debit_limit"] ) && ($user["balance_type"] == 1) ): $error = 1; $errorText= "Not enough balance";  
        else:
            $conn->beginTransaction();

            // Insert with advanced duration field
            $insert = $conn->prepare("INSERT INTO childpanels SET 
                 client_id=:c_id,
                 domain=:domain,
                 child_panel_currency=:currency,
                 child_panel_username=:username,
                 child_panel_password=:password,
                 charged_amount=:charged_amount,
                 duration_months=:duration_months,
                 child_panel_status=:status,
                 renewal_date=:renewal_date, 
                 created_on=:created_on,
                 child_panel_uqid=:uqid");

            $insert->execute(array(
               "c_id"           => $user["client_id"],
               "domain"         => $domain,
               "currency"       => $currency,
               "username"       => $username,
               "password"       => $password,
               "charged_amount" => $price,
               "duration_months"=> $duration_months,
               "status"         => "Pending",
               "renewal_date"   => $renewal_date,
               "created_on"     => date("Y-m-d H:i:s"),
               "uqid"           => md5(openssl_random_pseudo_bytes(16))
            )); 

            if( $insert ):
                $last_id = $conn->lastInsertId();
                
                $update = $conn->prepare("UPDATE clients SET balance=:balance, spent=:spent WHERE client_id=:id");
                $update->execute(array("balance"=>$user["balance"]-$price, "spent"=>$user["spent"]+$price, "id"=>$user["client_id"]));
                
                $insert2= $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
                $insert2->execute(array("c_id"=>$user["client_id"], "action"=>"#".$last_id." New Child Panel Order (".$duration_months." Months).", "ip"=>GetIP(), "date"=>date("Y-m-d H:i:s") ));
                
                if ( $update && $insert2 ):
                    $conn->commit();
                    
                    $user_query = $conn->prepare("SELECT * FROM clients WHERE client_id=:id");
                    $user_query->execute(array("id"=>$_SESSION["msmbilisim_userid"] ));
                    $user_updated = $user_query->fetch(PDO::FETCH_ASSOC);
                    
                    $order_data = [
                         'success' => 1,
                         'id'      => $last_id,
                         "link"    => $domain,
                         "quantity"=> $duration_months,
                         "price"   => $price,
                         "balance" => $user_updated["balance"]
                    ];
                    $_SESSION["data"]["services"]   = "Child Panel";
                    $_SESSION["data"]["categories"] = "Child Panels";
                    $_SESSION["data"]["childpanel"] = $order_data;
                    
                    header("Location:".site_url("child-panels"));
                    exit;
                else:
                    $conn->rollBack();
                    $error = 1; $errorText= "Order failed during account update.";
                endif;
            else:
                $conn->rollBack();
                $error = 1; $errorText= "Order failed to insert.";
            endif;
        endif;
    }  
endif;
?>