<?php

session_start();
include 'branch_connection.php';

if (!isset($_SESSION['userid'])) {
    header("Location: ../index.php");
    exit;
}

if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn->set_charset("utf8mb4");

// =====================
// CONFIG & MAIN DB
// =====================
$mainDbHost = 'localhost';
$mainDbUser = 'xtodo_systemsoft';
$mainDbPass = ';)u&S9wx6#xD87l^';
$mainDbName = 'xtodo_systemsoft';

$cpanelUser   = 'xtodo';
$cpanelToken  = '2OYC3BKRX9G1UMXRYZSCJR4IM4V448N3';
$cpanelDomain = 'xtodo.programersapps.com';

// Pagination
$itemsPerPage = 20;
$currentPage  = isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0 ? (int)$_GET['page'] : 1;
$offset       = ($currentPage - 1) * $itemsPerPage;
$message      = "";
$copyErrors   = [];

// Upload directory
$uploadDir = __DIR__ . '/uploads/branches/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

// =====================
// HELPER FUNCTIONS
// =====================
function handle_file_upload($fileInputName, $uploadDir) {
    if (!isset($_FILES[$fileInputName]) || $_FILES[$fileInputName]['error'] === UPLOAD_ERR_NO_FILE) return '';
    $f = $_FILES[$fileInputName];
    if ($f['error'] !== UPLOAD_ERR_OK) return '';
    $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg','jpeg','png','gif','pdf'];
    if (!in_array($ext, $allowed)) return '';
    $unique = time() . '_' . bin2hex(random_bytes(6));
    $filename = $unique . ".$ext";
    if (move_uploaded_file($f['tmp_name'], $uploadDir . $filename)) return $filename;
    return '';
}

function cpanel_api_call($url, $cpanelUser, $cpanelToken) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: cpanel {$cpanelUser}:{$cpanelToken}"]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    curl_close($ch);
    if ($resp === false) return ['error' => $err];
    $dec = json_decode($resp, true);
    return $dec ?: ['raw' => $resp];
}

// =====================
// DELETE BRANCH
// =====================
if (isset($_GET['delete_id']) && is_numeric($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    $res = $conn->query("SELECT logo1, logo2, franchiser_idcard, manager_idcard FROM branches WHERE id = $delete_id LIMIT 1");
    if ($res && $res->num_rows) {
        $row = $res->fetch_assoc();
        foreach (['logo1','logo2','franchiser_idcard','manager_idcard'] as $fn) {
            if (!empty($row[$fn]) && file_exists($uploadDir . $row[$fn])) @unlink($uploadDir . $row[$fn]);
        }
    }
    $conn->query("DELETE FROM branches WHERE id = $delete_id");
    header("Location: add-branch.php?page=$currentPage&msg=" . urlencode("Branch deleted successfully."));
    exit;
}

// =====================
// EDIT BRANCH (LOAD DATA)
// =====================
$editMode = false;
$editId = 0;
$values = [
    'company_name'=>'','branch_name'=>'','branch_type'=>'','logo1'=>'','logo2'=>'','address'=>'','bank_name'=>'','bank_details'=>'',
    'reg_date'=>'','start_date'=>'','end_date'=>'','amc_start'=>'','amc_end'=>'',
    'franchiser_name'=>'','franchiser_idcard'=>'','franchiser_address'=>'','franchiser_phone'=>'','franchiser_email'=>'',
    'manager_name'=>'','manager_idcard'=>'','manager_address'=>'','manager_phone'=>'','manager_email'=>''
];

if (isset($_GET['edit_id']) && is_numeric($_GET['edit_id'])) {
    $editId = (int)$_GET['edit_id'];
    $res = $conn->query("SELECT * FROM branches WHERE id = $editId LIMIT 1");
    if ($res && $res->num_rows) {
        $editMode = true;
        $row = $res->fetch_assoc();
        foreach ($values as $k=>$v) if (isset($row[$k])) $values[$k] = $row[$k];
    }
}

// =====================
// SAVE BRANCH
// =====================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postedEditId = (int)($_POST['edit_id'] ?? 0);
    $fields = ['company_name','branch_name','branch_type','address','bank_name','bank_details','reg_date','start_date','end_date','amc_start','amc_end',
        'franchiser_name','franchiser_address','franchiser_phone','franchiser_email',
        'manager_name','manager_address','manager_phone','manager_email'];
    foreach ($fields as $f) $$f = $conn->real_escape_string($_POST[$f] ?? '');

    // --- File uploads ---
    $logo1 = $logo2 = $franchiser_idcard = $manager_idcard = '';
    if ($postedEditId > 0) {
        $old = $conn->query("SELECT logo1, logo2, franchiser_idcard, manager_idcard FROM branches WHERE id = $postedEditId")->fetch_assoc();
        $logo1 = $old['logo1']; $logo2 = $old['logo2']; $franchiser_idcard = $old['franchiser_idcard']; $manager_idcard = $old['manager_idcard'];
    }
    foreach (['logo1','logo2','franchiser_idcard','manager_idcard'] as $fld) {
        $tmp = handle_file_upload($fld, $uploadDir);
        if ($tmp !== '') {
            $oldFile = ${$fld};
            if (!empty($oldFile) && file_exists($uploadDir.$oldFile)) @unlink($uploadDir.$oldFile);
            ${$fld} = $tmp;
        }
    }

    if ($company_name === '' || $branch_name === '' || $branch_type === '') {
        $message = "Please fill required fields.";
    } else {
        if ($postedEditId > 0) {
            // -------- UPDATE EXISTING --------
            $q = "UPDATE branches SET
                company_name='$company_name', branch_name='$branch_name', branch_type='$branch_type',
                address='$address', bank_name='$bank_name', bank_details='$bank_details',
                reg_date='$reg_date', start_date='$start_date', end_date='$end_date',
                amc_start='$amc_start', amc_end='$amc_end',
                franchiser_name='$franchiser_name', franchiser_address='$franchiser_address', franchiser_phone='$franchiser_phone', franchiser_email='$franchiser_email',
                manager_name='$manager_name', manager_address='$manager_address', manager_phone='$manager_phone', manager_email='$manager_email',
                logo1='$logo1', logo2='$logo2', franchiser_idcard='$franchiser_idcard', manager_idcard='$manager_idcard'
                WHERE id=$postedEditId";
            $conn->query($q);
            $message = "Branch updated successfully.";

            // --- Also update main leads DB ---
            $mainConn = mysqli_connect('localhost', 'xtodo_systemsoft', ';)u&S9wx6#xD87l^', 'xtodo_main_leads');
            if ($mainConn) {
                $mainConn->set_charset("utf8mb4");
                $bcRes = $conn->query("SELECT branchcode FROM branches WHERE id=$postedEditId");
                $branchcode_main = $bcRes->fetch_assoc()['branchcode'];
                $exists = $mainConn->query("SELECT id FROM branches WHERE branchcode='$branchcode_main' LIMIT 1");

                if ($exists && $exists->num_rows > 0) {
                    $updateQ = "
                        UPDATE branches SET
                            company_name='$company_name',
                            branch_name='$branch_name',
                            branch_type='$branch_type',
                            address='$address',
                            bank_name='$bank_name',
                            bank_details='$bank_details',
                            reg_date='$reg_date',
                            start_date='$start_date',
                            end_date='$end_date',
                            amc_start='$amc_start',
                            amc_end='$amc_end',
                            franchiser_name='$franchiser_name',
                            franchiser_address='$franchiser_address',
                            franchiser_phone='$franchiser_phone',
                            franchiser_email='$franchiser_email',
                            manager_name='$manager_name',
                            manager_address='$manager_address',
                            manager_phone='$manager_phone',
                            manager_email='$manager_email',
                            logo1='$logo1',
                            logo2='$logo2',
                            franchiser_idcard='$franchiser_idcard',
                            manager_idcard='$manager_idcard'
                        WHERE branchcode='$branchcode_main'
                    ";
                    $mainConn->query($updateQ);
                } else {
                    $insertQ = "
                        INSERT INTO branches (
                            company_name, branch_name, branch_type, address, bank_name, bank_details,
                            reg_date, start_date, end_date, amc_start, amc_end,
                            franchiser_name, franchiser_address, franchiser_phone, franchiser_email,
                            manager_name, manager_address, manager_phone, manager_email,
                            logo1, logo2, franchiser_idcard, manager_idcard, branchcode, created_at
                        ) VALUES (
                            '$company_name','$branch_name','$branch_type','$address','$bank_name','$bank_details',
                            '$reg_date','$start_date','$end_date','$amc_start','$amc_end',
                            '$franchiser_name','$franchiser_address','$franchiser_phone','$franchiser_email',
                            '$manager_name','$manager_address','$manager_phone','$manager_email',
                            '$logo1','$logo2','$franchiser_idcard','$manager_idcard',
                            '$branchcode_main', NOW()
                        )
                    ";
                    $mainConn->query($insertQ);
                }

                mysqli_close($mainConn);
            } else {
                error_log("Could not connect to xtodo_main_leads DB: " . mysqli_connect_error());
            }

        } else {
            // -------- INSERT NEW --------
            $q = "INSERT INTO branches (
                company_name, branch_name, branch_type, address, bank_name, bank_details,
                reg_date, start_date, end_date, amc_start, amc_end,
                franchiser_name, franchiser_address, franchiser_phone, franchiser_email,
                manager_name, manager_address, manager_phone, manager_email,
                logo1, logo2, franchiser_idcard, manager_idcard, created_at
            ) VALUES (
                '$company_name','$branch_name','$branch_type','$address','$bank_name','$bank_details',
                '$reg_date','$start_date','$end_date','$amc_start','$amc_end',
                '$franchiser_name','$franchiser_address','$franchiser_phone','$franchiser_email',
                '$manager_name','$manager_address','$manager_phone','$manager_email',
                '$logo1','$logo2','$franchiser_idcard','$manager_idcard',NOW()
            )";
            $conn->query($q);
            $new_branch_id = $conn->insert_id;

            // Branch code & DB creation
            $branch_code = 'BR' . str_pad($new_branch_id, 2, '0', STR_PAD_LEFT);
            $branch_name_part = strtoupper(substr(preg_replace('/[^A-Za-z]/', '', $branch_name), 0, 4)) ?: 'BR';
            $prefixedDb = $cpanelUser . "_" . $branch_code . "_" . $branch_name_part;

            // --- Insert to main leads DB ---
            $mainConn = mysqli_connect('localhost', 'xtodo_systemsoft', ';)u&S9wx6#xD87l^', 'xtodo_main_leads');
            if ($mainConn) {
                $mainConn->set_charset("utf8mb4");
                $insertQ = "INSERT INTO branches (
                    company_name, branch_name, branch_type, address, bank_name, bank_details,
                    reg_date, start_date, end_date, amc_start, amc_end,
                    franchiser_name, franchiser_address, franchiser_phone, franchiser_email,
                    manager_name, manager_address, manager_phone, manager_email,
                    logo1, logo2, franchiser_idcard, manager_idcard, branchcode, branch_db, created_at
                ) VALUES (
                    '$company_name','$branch_name','$branch_type','$address','$bank_name','$bank_details',
                    '$reg_date','$start_date','$end_date','$amc_start','$amc_end',
                    '$franchiser_name','$franchiser_address','$franchiser_phone','$franchiser_email',
                    '$manager_name','$manager_address','$manager_phone','$manager_email',
                    '$logo1','$logo2','$franchiser_idcard','$manager_idcard','$branch_code','$prefixedDb',NOW()
                )";
                $mainConn->query($insertQ);
                mysqli_close($mainConn);
            }

            $conn->query("UPDATE branches SET branchcode = '$branch_code', branch_db='$prefixedDb' WHERE id='$new_branch_id'");

            // --- cPanel DB creation ---
            $createUrl = "https://{$cpanelDomain}:2083/execute/Mysql/create_database?name=" . rawurlencode($prefixedDb);
            $apiRes = cpanel_api_call($createUrl, $cpanelUser, $cpanelToken);

            if (isset($apiRes['status']) && $apiRes['status'] == 1) {
                $assignUrl = "https://{$cpanelDomain}:2083/execute/Mysql/set_privileges_on_database?user=" . rawurlencode($mainDbUser) . "&database=" . rawurlencode($prefixedDb) . "&privileges=ALL%20PRIVILEGES";
                cpanel_api_call($assignUrl, $cpanelUser, $cpanelToken);
            } else {
                $copyErrors[] = "cPanel DB creation response: " . print_r($apiRes, true);
            }

            // --- Copy tables from template DB (xtodo_systemsoft) ---
            try {
                $targetConn = mysqli_connect($mainDbHost, $mainDbUser, $mainDbPass);
                $tablesRes = $conn->query("SHOW TABLES FROM `$mainDbName`");
                while ($tblRow = $tablesRes->fetch_row()) {
                    $tbl = $tblRow[0];
                    $createSql = "CREATE TABLE IF NOT EXISTS `{$prefixedDb}`.`{$tbl}` LIKE `{$mainDbName}`.`{$tbl}`";
                    mysqli_query($targetConn, $createSql);
                    $cntRes = $conn->query("SELECT COUNT(*) AS c FROM `$mainDbName`.`$tbl`");
                    $cnt = ($cntRes) ? (int)$cntRes->fetch_assoc()['c'] : 0;
                    if ($cnt > 0) {
                        $insertSql = "INSERT INTO `{$prefixedDb}`.`{$tbl}` SELECT * FROM `{$mainDbName}`.`$tbl`";
                        mysqli_query($targetConn, $insertSql);
                    }
                }
                mysqli_close($targetConn);
            } catch (Exception $e) {
                $copyErrors[] = $e->getMessage();
            }

            // --- Create connection file ---
            $connFile = __DIR__ . "/connection_branch_{$branch_code}.php";
            $fileContent = "<?php\n"
                . "\$dbHost = 'localhost';\n"
                . "\$dbUser = '" . addslashes($mainDbUser) . "';\n"
                . "\$dbPass = '" . addslashes($mainDbPass) . "';\n"
                . "\$dbName = '" . addslashes($prefixedDb) . "';\n"
                . "\$conn = mysqli_connect(\$dbHost, \$dbUser, \$dbPass, \$dbName);\n"
                . "if (!\$conn) { die('Database connection failed: ' . mysqli_connect_error()); }\n"
                . "\$conn->set_charset('utf8mb4');\n"
                . "?>";
            if (file_put_contents($connFile, $fileContent) === false) {
                $copyErrors[] = "Connection file not created (permission issue at $connFile)";
            }

            $message = empty($copyErrors) ? "New branch added; DB created ($prefixedDb) and tables copied; connection file created." : "New branch added; DB created ($prefixedDb) but some tables or file failed.";
        }
    }

    if (!empty($copyErrors)) error_log("Branch DB copy errors: " . implode(" | ", $copyErrors));
    header("Location: add-branch.php?page=$currentPage&msg=" . urlencode($message));
    exit;
}

// =====================
// FETCH LIST
// =====================
$totalItems = $conn->query("SELECT COUNT(*) AS t FROM branches")->fetch_assoc()['t'];
$totalPages = ceil($totalItems / $itemsPerPage);
$listRes = $conn->query("SELECT * FROM branches ORDER BY id DESC LIMIT $itemsPerPage OFFSET $offset");

if (isset($_GET['msg'])) $message = htmlspecialchars($_GET['msg']);
?>



<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Leads Programers International</title>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="author" content="DexignLab">
      <meta name="robots" content="index, follow">
      <meta name="format-detection" content="telephone=no">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="shortcut icon" type="image/png" href="assets/images/favicon.png">
      <link href="assets/vendor/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet">
      <link href="assets/vendor/bootstrap-datepicker-master/css/bootstrap-datepicker.min.css" rel="stylesheet">
      <link href="assets/vendor/owl-carousel/owl.carousel.css" rel="stylesheet">
      <link href="assets/css/jquery.localizationTool.css" rel="stylesheet">
      <link class="main-css" href="assets/css/style.css" rel="stylesheet">
      <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
   </head>
   <body>
      <div id="preloader">
         <div class="lds-ripple">
            <div></div>
            <div></div>
         </div>
      </div>
      <div id="main-wrapper">
         <div class="nav-header">
            <a href="index.html" class="brand-logo"><img src="assets/images/logo-02.svg" alt=""></a>
            <div class="nav-control">
               <div class="hamburger">
                  <span class="line"></span><span class="line"></span><span class="line"></span>
               </div>
            </div>
         </div>
         <div class="header">
            <div class="header-content">
               <nav class="navbar navbar-expand">
                  <div class="collapse navbar-collapse justify-content-between">
                     <div class="header-left">
                        <div class="dashboard_bar">
                           Add Branch
                        </div>
                     </div>
                     <ul class="navbar-nav header-right">
                        <li class="nav-item dropdown notification_dropdown">
                           <a class="nav-link bell dlab-theme-mode p-0" href="javascript:void(0);">
                           <i id="icon-light" class="fas fa-sun"></i>
                           <i id="icon-dark" class="fas fa-moon"></i>
                           </a>
                        </li>
                        <?php $title = "Php Header Footer"; include "logout.php"; ?>
                     </ul>
                  </div>
               </nav>
            </div>
         </div>
         <?php $title = "Php Header Footer"; include "header.php"; ?>
         <div class="content-body">
            <div class="container-fluid">
               <div class="row">
                  <div class="col-xl-12">
                     <div class="row">
                        <div class="col-xl-4">
                           <div class="card">
                              <div class="card-body">
                                 <div class="basic-form">
                                    <?php if ($message): ?>
                                        <div class="alert alert-info" style="white-space:pre-wrap;"><?php echo $message; ?></div>
                                    <?php endif; ?>
                                    <!-- Keep design identical; note enctype for files -->
                                    <form method="POST" action="" enctype="multipart/form-data">
                                       <input type="hidden" name="edit_id" value="<?php echo $editMode ? (int)$editId : 0; ?>">
                                       <div class="row">
                                          <div class="mb-3 col-md-13">
                                             <input type="text" name="company_name" class="form-control" placeholder="Company Name" value="<?php echo htmlspecialchars($values['company_name']); ?>" required>
                                          </div>
                                          <div class="mb-3 col-md-13">
                                             <input type="text" name="branch_name" class="form-control" placeholder="Branch Name" value="<?php echo htmlspecialchars($values['branch_name']); ?>" required>
                                          </div>
                                          <div class="mb-3 col-md-13">
                                             <select name="branch_type" class="default-select form-control wide" required id="branchSelect">
                                                <option value="" disabled <?php echo $values['branch_type']==''?'selected':''; ?>>Branch Type</option>
                                                <option value="Parental" <?php echo $values['branch_type']=='Parental'?'selected':''; ?>>Parental</option>
                                                <option value="Franchise" <?php echo $values['branch_type']=='Franchise'?'selected':''; ?>>Franchise</option>
                                             </select>
                                          </div>
                                          <div class=" col-md-13">
                                             <input type="file" name="logo1" class="form-control">
                                             <label for="" class="text-danger">Upload first logo</label>
                                             <?php if (!empty($values['logo1'])): ?><div class="mt-1"><small>Existing: <?php echo htmlspecialchars($values['logo1']); ?></small></div><?php endif; ?>
                                          </div>
                                          <div class=" col-md-13">
                                             <input type="file" name="logo2" class="form-control">
                                             <label for="" class="text-danger">Upload second logo</label>
                                             <?php if (!empty($values['logo2'])): ?><div class="mt-1"><small>Existing: <?php echo htmlspecialchars($values['logo2']); ?></small></div><?php endif; ?>
                                          </div>
                                          <div class="mb-3 col-md-13">
                                             <textarea name="address" class="form-control" placeholder="Address"><?php echo htmlspecialchars($values['address']); ?></textarea>
                                          </div>
                                          <div class="mb-3 col-md-13">
                                            <select id="bankSelect" name="bank_name" class="default-select form-control wide" required>
                                                <option value="" data-address="" disabled <?php echo $values['bank_name']==''?'selected':''; ?>>Select Bank</option>
                                                <?php
                                                $bankRes = $conn->query("SELECT * FROM banks WHERE status='Enable' ORDER BY bank_name");
                                                while($b = $bankRes->fetch_assoc()):
                                                    $selected = ($values['bank_name'] == $b['bank_name']) ? 'selected' : '';
                                                    $address = htmlspecialchars($b['address'] ?? '');
                                                ?>
                                                <option value="<?php echo htmlspecialchars($b['bank_name']); ?>" data-address="<?php echo $address; ?>" <?php echo $selected; ?>>
                                                    <?php echo htmlspecialchars($b['bank_name']); ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3 col-md-13">
                                            <textarea id="bankAddress" name="bank_details" class="form-control" placeholder="Bank Address"><?php echo htmlspecialchars($values['bank_details']); ?></textarea>
                                        </div>

                                          <div class="mb-3 col-md-13">
                                             <input id="reg_date" name="reg_date" class="form-control" placeholder="Registration Date" value="<?php echo htmlspecialchars($values['reg_date']); ?>">
                                          </div>
                                          <div class="mb-3 col-md-13">
                                             <input id="start_date" name="start_date" class="form-control" placeholder="Start Date" value="<?php echo htmlspecialchars($values['start_date']); ?>">
                                          </div>
                                          <div class="mb-3 col-md-13">
                                             <input id="end_date" name="end_date" class="form-control" placeholder="End Date" value="<?php echo htmlspecialchars($values['end_date']); ?>">
                                          </div>
                                          <div class="mb-3 col-md-13">
                                             <input id="amc_start" name="amc_start" class="form-control" placeholder="AMC Start Date" value="<?php echo htmlspecialchars($values['amc_start']); ?>">
                                          </div>
                                          <div class="mb-3 col-md-13">
                                             <input id="amc_end" name="amc_end" class="form-control" placeholder="AMC End Date" value="<?php echo htmlspecialchars($values['amc_end']); ?>">
                                          </div>
                                          <div id="franchiser-data" style="display:<?php echo ($values['branch_type']=='Franchise')?'block':'none'; ?>;">
                                            <div class="mb-3 col-md-13">
                                              <input type="text" name="franchiser_name" class="form-control" placeholder="Franchiser" value="<?php echo htmlspecialchars($values['franchiser_name']); ?>">
                                            </div>
                                            <div class=" col-md-13">
                                             <input type="file" name="franchiser_idcard" class="form-control">
                                             <label for="" class="text-danger">Upload ID Card</label>
                                             <?php if (!empty($values['franchiser_idcard'])): ?><div class="mt-1"><small>Existing: <?php echo htmlspecialchars($values['franchiser_idcard']); ?></small></div><?php endif; ?>
                                            </div>
                                            <div class="mb-3 col-md-13">
                                             <textarea name="franchiser_address" class="form-control" placeholder="Address"><?php echo htmlspecialchars($values['franchiser_address']); ?></textarea>
                                            </div>
                                            <div class="mb-3 col-md-13">
                                              <input type="text" name="franchiser_phone" class="form-control" placeholder="Phone Number" value="<?php echo htmlspecialchars($values['franchiser_phone']); ?>">
                                            </div>
                                            <div class="mb-3 col-md-13">
                                              <input type="email" name="franchiser_email" class="form-control" placeholder="E-mail" value="<?php echo htmlspecialchars($values['franchiser_email']); ?>">
                                            </div>
                                          </div>
                                          <div id="manager-data" style="display:<?php echo ($values['branch_type']=='Parental')?'block':'none'; ?>;">
                                            <div class="mb-3 col-md-13">
                                              <input type="text" name="manager_name" class="form-control" placeholder="Manager" value="<?php echo htmlspecialchars($values['manager_name']); ?>">
                                            </div>
                                            <div class=" col-md-13">
                                             <input type="file" name="manager_idcard" class="form-control">
                                             <label for="" class="text-danger">Upload ID Card</label>
                                             <?php if (!empty($values['manager_idcard'])): ?><div class="mt-1"><small>Existing: <?php echo htmlspecialchars($values['manager_idcard']); ?></small></div><?php endif; ?>
                                            </div>
                                            <div class="mb-3 col-md-13">
                                             <textarea name="manager_address" class="form-control" placeholder="Address"><?php echo htmlspecialchars($values['manager_address']); ?></textarea>
                                            </div>
                                            <div class="mb-3 col-md-13">
                                              <input type="text" name="manager_phone" class="form-control" placeholder="Phone Number" value="<?php echo htmlspecialchars($values['manager_phone']); ?>">
                                            </div>
                                            <div class="mb-3 col-md-13">
                                              <input type="email" name="manager_email" class="form-control" placeholder="E-mail" value="<?php echo htmlspecialchars($values['manager_email']); ?>">
                                            </div>
                                          </div>
                                       </div>
                                       <button type="submit" class="btn btn-primary w-100">
                                       <?php echo $editMode ? 'Update' : 'Submit'; ?></button>
                                    </form>
                                 </div>
                              </div>
                           </div>
                        </div>
                        <div class="col-xl-8">
                           <div class="table-responsive">
                              <table class="table table-hover table-responsive-sm">
                                 <thead>
                                    <tr>
                                       <th class="td-padding-no" style="width: 10px;">Branch</th>
                                       <th class="td-padding-no" style="width: 10px;">Code</th>
                                       <th class="td-padding-no" style="width: 100px;">Contact Person</th>
                                       <th class="td-padding-no" style="width: 100px;">Mobile</th>
                                       <th class="td-padding-no" style="width: 100px;">Reg Date</th>
                                       <th class="td-padding-no" style="text-align: left!important;">Action</th>
                                    </tr>
                                 </thead>
                                 <tbody>
                                    <?php if ($listRes && $listRes->num_rows): ?>
                                      <?php while ($r = $listRes->fetch_assoc()): ?>
                                        <tr>
                                           <td class="td-padding-no"><?php echo htmlspecialchars($r['company_name'] . ($r['branch_name'] ? ' - ' . $r['branch_name'] : '')); ?></td>
                                           <td class="td-padding-no"><?php echo 'BR' . str_pad($r['id'], 2, '0', STR_PAD_LEFT); ?></td>
                                           <td class="td-padding-no"></td>
                                           <td class="td-padding-no"><?php echo htmlspecialchars($r['manager_phone']); ?></td>
                                           <td class="td-padding-no"><?php echo htmlspecialchars($r['reg_date']); ?></td>
                                           <td class="td-padding-no" style="text-align:center;">
                                              <span style="gap:2px;width: 100%;text-align:center;" class="d-flex">
                                                 <a href="add-branch.php?edit_id=<?php echo (int)$r['id']; ?>&page=<?php echo $currentPage; ?>" title="Edit" class="text-warning me-3"><i class="fa fa-edit"></i></a>
                                                 <a href="add-branch.php?delete_id=<?php echo (int)$r['id']; ?>&page=<?php echo $currentPage; ?>" title="Delete" style="color:#dc3545;" onclick="return confirm('Are you sure you want to delete this branch?');"><i class="fa fa-trash"></i></a>
                                              </span>
                                           </td>
                                        </tr>
                                      <?php endwhile; ?>
                                    <?php else: ?>
                                      <tr><td colspan="6">No branches found.</td></tr>
                                    <?php endif; ?>
                                 </tbody>
                              </table>
                           </div>
                           <!-- Pagination -->
                           <nav>
                              <ul class="pagination">
                                 <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                                    <li class="page-item <?php echo $p==$currentPage ? 'active' : ''; ?>">
                                       <a class="page-link" href="add-branch.php?page=<?php echo $p; ?>"><?php echo $p; ?></a>
                                    </li>
                                 <?php endfor; ?>
                              </ul>
                           </nav>
                        </div>
                     </div>
                  </div>
               </div>
            </div>

            <script>
            
                const bankSelect = document.getElementById('bankSelect');
                const bankAddress = document.getElementById('bankAddress');
                
                bankSelect.addEventListener('change', function() {
                    const selectedOption = bankSelect.options[bankSelect.selectedIndex];
                    bankAddress.value = selectedOption.getAttribute('data-address') || '';
                });

            
               const select = document.getElementById('branchSelect');
               const franchiserDiv = document.getElementById('franchiser-data');
               const managerDiv = document.getElementById('manager-data');

               select.addEventListener('change', function() {
                 if(this.value === 'Franchise') {
                   franchiserDiv.style.display = 'block';
                   managerDiv.style.display = 'none';
                 } else if(this.value === 'Parental') {
                   managerDiv.style.display = 'block';
                   franchiserDiv.style.display = 'none';
                 } else {
                   franchiserDiv.style.display = 'none';
                   managerDiv.style.display = 'none';
                 }
               });
            </script>
            <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
            <script>
               flatpickr('#reg_date', { dateFormat: 'Y-m-d' });
               flatpickr('#start_date', { dateFormat: 'Y-m-d' });
               flatpickr('#end_date', { dateFormat: 'Y-m-d' });
               flatpickr('#amc_start', { dateFormat: 'Y-m-d' });
               flatpickr('#amc_end', { dateFormat: 'Y-m-d' });
            </script>
         </div>
         <?php $title = "Php Header Footer"; include "footer.php"; ?>
      </div>

      <script src="assets/vendor/global/global.min.js"></script>
      <script src="assets/vendor/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
      <script src="assets/vendor/bootstrap-datepicker-master/js/bootstrap-datepicker.min.js"></script>
      <script src="assets/vendor/apexchart/apexchart.js"></script>
      <script src="assets/vendor/chartjs/chart.bundle.min.js"></script>
      <script src="assets/vendor/peity/jquery.peity.min.js"></script>
      <script src="assets/js/dashboard/dashboard-1.js"></script>
      <script src="assets/vendor/owl-carousel/owl.carousel.js"></script>
      <script src="assets/js/jquery.localizationTool.js"></script>
      <script src="assets/js/translator.js"></script>
      <script src="assets/js/custom.min.js"></script>
      <script src="assets/js/dlabnav-init.js"></script>
      <script src="assets/js/demo.js"></script>
   </body>
</html>
<?php
// close connection
$conn->close();
?>
