<?php

namespace PHPMaker2026\Ballot2026;
?>
<? ?>
<?php
$leftpanel = $MBSingleDiv = $MBStart = $MBHead = $MBloop = $MTNota = $MBloopClose = $MBSingleDivClose = $MBMultiDiv = $MBMultiDivClose = $MB = $MBhtml = $PBSingleDiv = $PBStart = $PBHead = $PBloop = $PTNota = $PBloopClose = $PBSingleDivClose = $PBMultiDiv = $PBMultiDivClose = $PB = $PBhtml = $EVM = $EVMhtml = $cond = $cond2 = '';
$PPL = $PPT = 0;
$i = 0;
$CUN = CurrentUserName();
$CUID = CurrentUserID();
$CDT = CurrentDatetime();
$CD = CurrentDate();

$BT = $_GET['BT'];
$ET = $_GET['ET'];
$NU = (int) $_GET['NU'] ?? 0;
$SetNo = $_GET['setno'] ?? 0;
$ID = $_GET['id'] ?? 0;
$RO = $_GET['RO'] ?? 0;
$CO = $_GET['CO'] ?? 0;
$HI = $_GET['HI'] ?? 420;
$WI = $_GET['WI'] ?? 297;
$PL = $_GET['PL'] ?? 0;
$PW = $_GET['PW'] ?? 0;
$PG = $_GET['PG'] ?? 0;
$PGTL = $_GET['PGTL'] ?? 0;
$GAP = $_GET['GAP'] ?? 13;
$POS = $_GET['POS'] ?? 0;
$BImage = $_GET['BImage'] ?? 0;
$Proof = $_GET['PR'] ?? 0;

//Plate Gripper
if ($PL && $PW && $PG)
{
    if($PGTL==1) //Plate Gripper (Top to Ballot)
    {
$GRDiv='
    <div style="width:'.$PL.'mm; height:'.$PW.'mm; font-size:0; border-left:2px solid black; background:
        linear-gradient(#000,#000) left top/'.$PG.'mm 1px no-repeat,
        linear-gradient(#000,#000) left center/'.$PG.'mm 1px no-repeat,
        linear-gradient(#000,#000) left bottom/'.$PG.'mm 1px no-repeat;">';
    $PPL = $PG;    
    $PPT =     (($PW - $HI)/2); 
    }
    elseif($PGTL==2) //Plate Gripper (Left to Ballot)
    {
$GRDiv='
    <div style="width:'.$PW.'mm; height:'.$PL.'mm; font-size:0">
        <div style="width:'.$PW.'mm; height:'.$PG.'mm; border-top:.25px solid #000; background:repeating-linear-gradient(to right, #000 0, #000 .25px, transparent 2px, transparent '.($PW/2).'mm); background-position: 0 0, 0 0, 0 0; background-repeat: repeat-x;">
        </div>';
    $PPL = (($PW - $WI)/2);
    }
$GRDivClose = '</div>';
}

// Fetch Data Conditions
if($SetNo != 0)
{
    $cond = "where `set_no` IN ($SetNo) and `election_info`.`candidate` > 0 and `election_type` = $ET and `ballot_type` = $BT ";
    $cond2 = "where `set_no` IN ($SetNo) and `ei`.`candidate` > 0 and `election_type` = $ET and `ballot_type` = $BT ";} 
elseif($ID != 0) 
{
    $cond = "where `election_info`.`id` IN ($ID) and `election_info`.`candidate` > 0 and `election_type` = $ET and `ballot_type` = $BT ";
    $cond2 = "where `ei`.`id` IN ($ID) and `ei`.`candidate` > 0 and `election_type` = $ET and `ballot_type` = $BT ";
}

//Serial Number Conditions
if($NU!=0) 
{
    $join = ' left join `number` on `number`.`id` <= `election_info`.`quantity` ';
} 
else 
{
    $join = ' left join `number` on `number`.`id` = `election_info`.`quantity` ';
}
$VoteData = ExecuteRows("SELECT  `election_info`.`id`, (count(`election_info`.`constituency`) + 1)as count, `election_info`.`constituency_e` AS `constituency_e`, `election_info`.`constituency`, lpad(`election_info`.`ward`, 2, 0) as `ward`, `election_info`.`quantity`, `election_info`.`candidate` AS `TotalCandidate`,  `election_info`.`set_no`, `election_info`.`ballot_type`, (SELECT MAX(if(`ei`.`quantity` = 0, 1, `ei`.`quantity`)) FROM `election_info` `ei`  $cond2) AS MaxQuantity, max(`postal_ballot`) as `postal_ballot`  FROM `candidates` LEFT JOIN `election_info` ON `election_info`.`id` = `candidates`.`constituency` $join $cond group by `candidates`.`constituency` order by `election_info`.`candidate` Asc");
$POS = (int)$VoteData[0]['postal_ballot'];

//Serial Number Start and Max Number Conditions
if($NU!=0) 
{
    $Start_N   = 100001; 
    $MaxQuantity = (int)$VoteData[0]['MaxQuantity'] + (int)$Start_N ;
} 
else 
{
    $Start_N   = 0; 
    $MaxQuantity = 1 ;    
}

//EVM
if (($BT == 10101 || $BT == 10102) && $BImage == 0  && !empty($VoteData))
{
    for ($x = $Start_N; $x < $MaxQuantity; $x++) 
    {
        if ($x==0) $sno = ''; else $sno=$x;

        foreach($VoteData as $Vd) 
        {
            $ConstituencyID     = $Vd['id'];
            $ConstituencyName     = $Vd['constituency'];
            $WarNumber        = $Vd['ward'];
            $TotalCandidate    = $Vd['TotalCandidate'];
            $Quantity          = $Vd['quantity'];
            $BallotType     = $Vd['ballot_type'];

            $text = ExecuteRow("SELECT `ballot_head`, `line_01`, `line_02`, `line_03`, `nota_text`, `serial_text`, `image`, `sign_series`, `max_c_row` FROM `misc` WHERE id = f");
            $head             = $text['ballot_head'];
            $bimage         = $text['image'];
            $SS             = $text['sign_series'] ?? 0;    
            $serialtext        = $text['serial_text'];
            $notatext         = $text['nota_text'];
            $ManualBtext    = $text['line_01'] .  $ConstituencyName;
            $ManualBtext2    = ($text['line_02'] == 0) ? '&nbsp;&nbsp;' :$text['line_02'] . $WarNumber;
            $ManualBtext3    = $text['line_03'];
            $maxcrow       =$text['max_c_row'];
            $sheetno             = "'khV ua- % 1";
            $EVMleftpanel    = $text['line_01'] .  $ConstituencyName . ' / ' . $text['line_03'];
            $EVMcol         = $TotalCandidate/$maxcrow;
    
            $s = 0;
            if ($BT == 10101)
            {
                $height = (461.50 - $s);
                $width = 138;
                $top = 28.35;
                $loop = 103.94;
                $image = ($loop * .75);
                $line = 3.78;
                $left = 20;
                $right = ($width-$left);
            } elseif ($BT == 10102) {
                $height = (1731- $s);
                $width = 521.57;
                $top = 48;
                $loop = 96;
                $image = ($loop * .75);
                $line = 7.56;
                $left = 20;
                $right = ($width-$left);
            }

            if ($TotalCandidate > (15+1))
            {
                $sheetno = "'khV ua- % 1";
            } else {
                $sheetno = "";
            }

$EVMMultiDiv='
<div id="MultiDiv" style="width:'.($CO*$width).'mm; height: '.($RO*$height).'mm">';
$EVMSingleDiv='
    <div id="SingleDiv" align="left" style="width:'.$width.'mm; height: '.$height.'mm; float:left; margin-bottom:48px;">
        <div id="LeftDiv" align="left" style="width: '.$left.'mm; border-right: 2px solid black;position:absolute; height: '.$height.'mm;">';
$EVMLeftDiv='            
            <div style="transform: rotate(-90deg);margin-top: 275px;position: relative;margin-right: -36px;">
                <p style="font-size: 15px;  font-weight: Bold; width:251px">' . $serialtext . '  '  . $sno . '</p> 
            </div>
            <div style="transform: rotate(-90deg);margin-top: 550px;position: relative;margin-right: -36px;">
                <p style="font-size: 15px; font-weight: Bold; width:351px;">' . $EVMleftpanel .'</p>
            </div>
            <div style="transform: rotate(-90deg);margin-top: 550px;position: relative;margin-right: -36px;">
                <p style="font-size: 15px; font-weight: Bold; width:351px;">' . $EVMleftpanel .'</p>
            </div>
            <div style="transform: rotate(-90deg);margin-top: 125px;position: relative;margin-right: -36px;">
                <p style="font-size: 20px;width:100px">' . $sheetno .'</p>
            </div>
        </div>'; 
$EVMTopDiv='            
        <div id="TopDiv" align="left" style="width:447px;margin-left:'.$left.'mm;">    
            <div style="width:447px; height:'.$top.'px;">
                <div style="width:100%; height:100%;">
                </div>
            </div>';
$EVMLoopStart='    
            <table style="border-collapse: collapse;" border="0" width="447">
                <tbody>';
                    $Cname = ExecuteRows("SELECT candidates.`s_no`, candidates.`cname`, `line2`, candidates.`sign` FROM `candidates` where `candidates`.`constituency` = $ConstituencyID");
$EVMLoop='';
                foreach($Cname as $Cn)
                {

$EVMLoop.='            <tr style="border-top:2px solid #000;">
                        <td style="width:15%" align="left" valign="center" height="' . $loop . '"><span style="padding-left:20px; font-size: 18px; font-weight: Bold">'. $Cn['s_no'] . '.</span>
                        </td>';
                    if     ($Cn['line2'] == NULL)
                    {
$EVMLoop.='                <td style="width:55%" align="left" valign="center"  height="' .$loop . '"><span style="padding-left:0px; font-size: 18px; font-weight: Bold">'. $Cn['cname'] . '</span>
                        </td>';
                    }
                    else
                    {
$EVMLoop.='                <td style="width:55%" align="left" valign="center"  height="' .$loop . '"><span style="padding-left:0px; font-size: 18px; font-weight: Bold">'. $Cn['cname']. '<br><span style="font-size:12px">' . $Cn['line2'] . '</span></span>
                        </td>';
                    }
$EVMLoop.='                <td style="width:25%" align="center" height="' . $loop . '">
                            <img src=".p_uploads/sign/'. $Cn['sign'].'" height="' .$image . '"/>
                        </td>
                        <td style="width:5%" height="'. $loop .'">
                        </td>
                    </tr>';
                } 
$EVMNota='            <tr style="border-top:2px solid #000; border-bottom: 2px solid #000;">
                        <td style="width:15%" align="left" valign="center" height="' .$loop . '"><span style="padding-left:20px; font-size: 18px; font-weight: Bold;">'. $TotalCandidate . '.</span>
                        </td>
                        <td style="width:55%" align="left" valign="center" height="' . $loop . '"><span style="padding-left:0px; font-size: 18px; font-weight: Bold">' . $notatext . '</span></td>
                        <td style="width:25%" align="center" height="' . $loop . '" style="border-bottom: 2px solid #000;">
                            <img src=".p_uploads/sign/Nota.jpg"  height="' .$image . '"/>
                        </td>
                        <td width="5%" height=' ."$loop" . '></td>
                    </tr>';             
$EVMLoopClose='    </tbody>
            </table>';
$EVMTopDivClose='                        
        </div>';
$EVMSingleDivClose='
    </div>';
        $EVMhtml_tmp =     $EVMSingleDiv.$EVMLeftDiv.$EVMTopDiv.$EVMLoopStart.$EVMLoop.$EVMNota.$EVMLoopClose.$EVMTopDivClose.$EVMSingleDivClose;
        $EVMhtml.= $EVMhtml_tmp;
        $i++;
        }

$EVMMultiDivClose='    
</div>';

//Page Break    
        if ($i==($CO*$RO)) {
            $PB ='<div class="page-break-after"></div>';
            $i=0;
        } else {
            $PB='';
        }
        
        if(isset($GRDiv)) {
            $EVM = $GRDiv.$EVMMultiDiv.$EVMhtml.$EVMMultiDivClose.$PB.$GRDivClose;
        } else {
            $EVM = $EVMMultiDiv.$EVMhtml.$EVMMultiDivClose.$PB;        
        }
        $EVMhtml ='';
        echo $EVM;
    }
}


// Manual Ballot Type
if (($BT == 10103 && !empty($VoteData)) || ($Proof == 1 && $POS == 1))
{
    $MBwidth = 101.6;
    $cnt = 0;
    $BSec = 1;
    for ($x = $Start_N; $x < $MaxQuantity; $x++) 
    {
        if ($x==0) $sno = ''; else $sno=$x;
        foreach($VoteData as $Vd) 
        {    
            $ConstituencyID     = $Vd['id'];
            $ConstituencyName     = $Vd['constituency'];
            $WarNumber        = $Vd['ward'];
            $TotalCandidate    = $Vd['TotalCandidate'];
            $Quantity          = $Vd['quantity'];
            $BallotType     = $Vd['ballot_type'];

            $text = ExecuteRow("SELECT `ballot_head`, `line_01`, `line_02`, `line_03`, `nota_text`, `serial_text`, `image`, `sign_series`, `max_c_row` FROM `misc` WHERE id = $ET");
            $head             = $text['ballot_head'];
            $bimage         = $text['image'];
            $SS             = $text['sign_series'] ?? 0;    
            $serialtext        = $text['serial_text'];
            $notatext         = $text['nota_text'];
            $ManualBtext    = $text['line_01'] .  $ConstituencyName;
            $ManualBtext2    = ($text['line_02'] == 0) ? '&nbsp;&nbsp;' :$text['line_02'] . $WarNumber;
            $ManualBtext3    = $text['line_03'];    
            $maxcrow        = $text['max_c_row'] ?? 9;
            $Bcol           = ceil($TotalCandidate/$maxcrow);
            $Brow           = ceil($TotalCandidate/$Bcol);
            $VStrip         = (($Bcol - 1) * 10);
            if ($POS == 1)
            {
                $PostalSeprator='
                <div>
                    <div class="stripe-container-postal"></div>
                    <div class="separator-line"></div>
                    <div class="stripe-container-postal"></div>
                </div>';
            }
            else
            {
                $PostalSeprator='';
            }
            
            //Panch
            if ($ET == 10208 && $bimage == 0)
            {
                $leftpanel    = $head . ' / ' . $ConstituencyName . ' / '. $text['line_02'] . $WarNumber. ' / ' . $text['line_03'];
            }
            //Sarpanch
            elseif ($ET == 10207 && $bimage == 0) 
            {
                $leftpanel    = $head . ' / ' . $ConstituencyName . ' / ' . $text['line_03'];
            }
        }
$MBMultiDiv='
<div id="MultiDiv" style="width:'.((101.6 * $CO)+$PPL+$VStrip).'mm; height:'.$HI.'mm; font-size:0; padding-left:'.$PPL.'mm; padding-top:'.$PPT.'mm">';
$MBSingleDiv ='
    <div align="left" style="width:'.(($MBwidth * $Bcol)+$VStrip).'mm; display:inline-block; vertical-align: top">'; 
$MBStart='
        <div style="width:'.(($MBwidth * $Bcol)+$VStrip).'mm;">
            <div style="width:'.(($MBwidth * $Bcol)+$VStrip).'mm; height:48px;"><span style="font-size:6px">|</span></div>
        </div>';
$MBHead='
        <table style="border-collapse: collapse;border-bottom: 2px solid #000; border-top: 2px solid #000; width:'.(($MBwidth * $Bcol)+$VStrip).'mm">
            <tbody>
                <tr>
                    <td align="left" valign="Top" rowspan="2" style="width:31.75mm; font-size: 14px; padding-left: 35px";>
                    <strong>No. <br><br><span style="font-size:18px">'.$sno.'</span></strong>
                    </td>
                </tr>

                <tr>    
                    <td align="right" height="96">
                        <p style="padding-right: 35px; line-height: 1.7; padding-top: 7px; font-weight: Bold; font-size: 12px">' . $ManualBtext . '</BR>' .$ManualBtext2 .  '</BR>' . $ManualBtext3 . '</p>
                    </td>
                </tr>
            </tbody>
        </table>';
        
$MBloop='
        <table style="border-collapse: collapse; width: 101.6mm" border="0"><tbody>';
        
        ExecuteStatement("UPDATE candidates c JOIN (SELECT id, ROW_NUMBER() OVER (ORDER BY cname) AS new_sort FROM candidates WHERE constituency = $ConstituencyID) x ON c.id = x.id SET c.s_no = x.new_sort, c.sort = x.new_sort");
$Cname = ExecuteRows("SELECT candidates.`s_no`, `sort`, candidates.`cname`, `line2`, candidates.`sign` FROM `candidates` where `candidates`.`constituency` = $ConstituencyID order by `s_no`");

            foreach($Cname as $Cn)
            {
                $cnt++;
                if ($cnt > $Brow)
                {
                   $BSec++;
                    break;
                }
                if ($Cn['sign'] == 0)
                    $sign = ($Cn['s_no'] + $SS)  . '.jpg';
                else
                    $sign = $Cn['sign'];
                    
if ($Cn['line2'] == NULL)
{
$totalRows = $TotalCandidate;
$Bcol = min($Bcol, 6);

// Balanced distribution
$MaxCountRow  = ceil(($TotalCandidate) / $Bcol);

$extra = $TotalCandidate % $Bcol;
$ColumnData = [];
$offset = 0;

for ($i = 0; $i < $Bcol; $i++)
{
    $ColumnData[$i] = array_slice($Cname, $offset, $MaxCountRow);
    $offset += $MaxCountRow;
}
$MBloop = '
<table border="0" cellpadding="0" cellspacing="0">
<tr>';

foreach ($ColumnData as $col => $Data)
{
    
    $MBloop .= '
    <td valign="top">
        <table border="0" cellpadding="0" cellspacing="0">';

    foreach ($Data as $Cn)
    {
        if ($Cn['sign'] == 0)
            $sign = ($Cn['s_no'] + $SS) . '.jpg';
        else
            $sign = $Cn['sign'];

        if ($Cn['line2'] == NULL)
        {
            $MBloop .= '
            <tr>
                <td align="left" valign="center" width="220" height="96">
                    <p style="padding-top:20px;padding-left:35px;font-weight:bold;font-size:18px;">
                        '.$Cn['cname'].'
                    </p>
                </td>
                <td align="center" width="172" height="96">
                    <img src=".p_uploads/sign/'.$sign.'" height="75" />
                </td>
            </tr>';
        }
        else
        {
            $MBloop .= '
            <tr>
                <td align="left" valign="center" width="220" height="96">
                    <p style="padding-left:35px;padding-top:15px;font-weight:bold;font-size:18px;">
                        '.$Cn['cname'].'<br>
                        <span style="font-size:12px;">'.$Cn['line2'].'</span>
                    </p>
                </td>
                <td align="center" width="172" height="96">
                    <img src=".p_uploads/sign/'.$sign.'" height="75" />
                </td>
            </tr>';
        }

        if ($Cn['sort'] == 1)
        {
            $MBloop .= '
            <tr>
                <td colspan="2" height="48">
                    <div class="stripe-container">
                        <div class="stripe-box">
                            <span class="stripe-text">'.$head.'</span>
                        </div>
                    </div>
                </td>
            </tr>';
        }
        else
        {
             if ($Cn['sort'] % $Brow != 0)
             {
            $MBloop .= '
            <tr>
                <td colspan="2" height="48">
                    <div class="stripe-container">
                    </div>
                        </div>
                </td>
            </tr>';
             }
        }
    }

    // LAST COLUMN ONLY
    if ($col == count($ColumnData) - 1)
    {
        // NOTA
        $MBloop .= '
        <tr>
            <td align="left" valign="center" width="220" height="96">
                <p style="padding-left:25px;font-weight:bold;font-size:18px">
                    '.$notatext.'
                </p>
            </td>
            <td align="center" width="172" height="96">
                <img src=".p_uploads/sign/Nota.jpg" height="75" />
            </td>
        </tr>';

        // Fill remaining rows with stripes
        $UsedRows  = count($Data) + 1; // +1 for NOTA
        $EmptyRows = ($Brow == $UsedRows) ? 0 : ((($Brow - $UsedRows) * 2)+1);

        for ($e = 1; $e <= $EmptyRows; $e++)
        {
            $MBloop .= '
            <tr>
                <td colspan="2" height="48">
                    <div class="stripe-container"></div>
                </td>
            </tr>';
        }
    }

    $MBloop .= '
        </table>
    </td>';

    // Vertical divider between columns
    if ($col < count($ColumnData) - 1)
    {
        $MBloop .= '
        <td class="stripe-containerV"></td>';
    }
}

$MBloop .= '
</tr>
</table>
';    
}

            }

$MTNota = '';
$MBloopClose ='
        </table>
        <div style="width:'.(($MBwidth * $Bcol)+$VStrip).'mm; height:'.$GAP.'mm; border-top:2px solid"></div>';
        
        $title = '<div class="stripe-container">
    <span class="stripe-text">पंच चुनाव</span>
</div>';
$MBSingleDivClose ='            
    </div>';

            IF($POS == 1)
            {
                IF(($Proof == 1) && ($BT == 10101 || $BT == 10102))
                {
                    $MBhtml_tmp = $MBSingleDiv.$MBStart.$MBHead.$PostalSeprator.$MBHead.$MBloop.$MTNota.$MBloopClose.$MBSingleDivClose;
                }
                elseif(($Proof == 1) && ($BT == 10103))
                {
                $MBhtml_tmp = $MBSingleDiv.$MBStart.$MBHead.$MBloop.$MTNota.$MBloopClose.$MBSingleDivClose;
                $MBhtml_tmp .= $MBSingleDiv.$MBStart.$MBHead.$PostalSeprator.$MBHead.$MBloop.$MTNota.$MBloopClose.$MBSingleDivClose;
                }
            }
            else
            {
                $MBhtml_tmp = $MBSingleDiv.$MBStart.$MBHead.$MBloop.$MBloopClose.$MBSingleDivClose;
            }    
            $MBhtml.= $MBhtml_tmp;    
            $i++;
            if ($i==($CO))
            {
                //$MBRowGap = '<div style="height:'.$GAP.'mm; ></div>';    
                $PB ='</div><div class="page-break-after"></div>';
                $i=0;
            }
        }
    }
$MBMultiDivClose='
</div>';
    if ($i==($CO*$RO))
    {
        $PB ='<div class="page-break-after"></div>';
        $i=0;
    }
    else
    {
        $PB='';
    }
    
    if(isset($GRDiv))
        $MB.= $GRDiv.$MBMultiDiv.$MBhtml.$MBMultiDivClose.$PB.$GRDivClose;
    else
        $MB.= $MBMultiDiv.$MBhtml.$MBMultiDivClose.$PB;        
    $MBhtml ='';
echo $MB;

?>

<style>
.stripe-container {
    width: 4in;
    height: 0.5in;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    background: repeating-linear-gradient(to bottom, black 0px, black .25px, white 1px, white 3px);
}

.stripe-container-postal {
    width: 4in;
    height: 0.17in;
    display: flex;
    align-items: center;
    justify-content: center;
    background: repeating-linear-gradient(to bottom, black 0px, black .05px, white 1px, white 3px);
}

.separator-line {
    width: 4in;
    height: 0.16in;/* total gap */
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
}
.separator-line::before {
    content: "";
    width: 100%;
    border-top: 2px dashed #000;
}

.stripe-box {
    height : 0.38in;
    background: #ffffff; /* make it pure white */
    padding: 2px 80px;
    border-radius: 4px;
    border: 0px solid #999;
    position: relative;
    z-index: 2; /* important */
}
.stripe-box::before {
    margin-top: -1px;
    content: "";
    position: absolute;
    inset: 0;
    background: #ffffff;
    z-index: -1;
}

.stripe-text {
    font-size: 24px;
    font-weight: bold;
    font-family: 'Noto Sans Devanagari', Arial, sans-serif;
    color: #000;
}

.name-text {
    font-size: 18px;
    font-weight: bold;
    font-family: 'Noto Sans Devanagari', Arial, sans-serif;
    color: #000;
}

.stripe-containerV{
    width:10mm;
    min-width:10mm;
    padding:0;
    background:repeating-linear-gradient(
        to right,
        black 0px,
        black 0.25px,
        white 1px,
        white 3px
    );
}

.page-break-after {
    page-break-after: always;
    break-after: page;
}

@media print {
    .page-break {
        display: block;
        break-before: page;
        page-break-before: always;
}

.no-break {
        break-inside: avoid;
        page-break-inside: avoid;
}
</style>
<script type="text/javascript">
//window.print()
</script>
