<?php
session_start();
$conn = new mysqli('ic-demo-db-instance.cwtxvqg3ca0c.us-east-1.rds.amazonaws.com', 'icdemoadmin', 't8wQ{jMJu?PVXKVRkQ8HZHxHw', 'jy_election_results', 3306);
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

// Handle save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['constituency_id'])) {
    $cid = (int)$_POST['constituency_id'];
    $winner = !empty($_POST['winner_candidate_id']) ? (int)$_POST['winner_candidate_id'] : null;
    $lead_count = (int)$_POST['lead_count'];
    $votes = (int)$_POST['votes'];
    $status = $_POST['status'];

    if ($winner) {
        $stmt = $conn->prepare("UPDATE constituency SET winner_candidate_id = ?, lead_count = ?, status = ? WHERE id = ?");
        $stmt->bind_param("iisi", $winner, $lead_count, $status, $cid);
        $stmt->execute();
        $stmt->close();
        $stmt2 = $conn->prepare("UPDATE candidates SET votes = ? WHERE id = ?");
        $stmt2->bind_param("ii", $votes, $winner);
        $stmt2->execute();
        $stmt2->close();
    } else {
        $stmt = $conn->prepare("UPDATE constituency SET winner_candidate_id = NULL, lead_count = ?, status = ? WHERE id = ?");
        $stmt->bind_param("isi", $lead_count, $status, $cid);
        $stmt->execute();
        $stmt->close();
    }

    // Generate static HTML
    generateResultsHtml($conn);

    $_SESSION['saved_id'] = $cid;
    header("Location: index.php");
    exit;
}

function indianNumberFormat($num) {
    $num = (int)$num;
    if ($num < 1000) return (string)$num;
    $last3 = str_pad($num % 1000, 3, '0', STR_PAD_LEFT);
    $rest = (int)($num / 1000);
    $parts = [];
    while ($rest >= 100) {
        $parts[] = str_pad($rest % 100, 2, '0', STR_PAD_LEFT);
        $rest = (int)($rest / 100);
    }
    $parts[] = (string)$rest;
    return implode(',', array_reverse($parts)) . ',' . $last3;
}

function generateResultsHtml($conn) {
    $result = $conn->query("
        SELECT c.id, c.name AS const_name, c.lead_count, c.status,
               d.name AS district_name, d.id AS district_id,
               ca.name AS candidate_name, ca.votes,
               p.name AS party_name, p.logo AS party_logo,
               a.name AS alliance_name, a.color AS alliance_color
        FROM constituency c
        JOIN ref_districts d ON c.district_id = d.id
        LEFT JOIN candidates ca ON c.winner_candidate_id = ca.id
        LEFT JOIN party p ON ca.party_id = p.id
        LEFT JOIN alliance a ON ca.alliance_id = a.id
        ORDER BY d.id, c.id
    ");

    $data = [];
    while ($row = $result->fetch_assoc()) {
        $data[$row['district_id']][] = $row;
    }
    // Build district tag bar
    

    $html .= "<table class=\"results-table\">\n<thead>\n<tr>\n<th>മണ്ഡലം</th>\n<th>സ്ഥാനാർത്ഥി</th>\n<th>പാർട്ടി</th>\n<th>സ്ഥിതി</th>\n</tr>\n</thead>\n<tbody>\n";
    foreach ($data as $districtId => $rows) {
        $distName = htmlspecialchars($rows[0]['district_name']);
        $html .= " \n<tr class=\"district-header\" id=\"district-{$districtId}\">\n<td colspan=\"4\" class=\"title normal_title\">{$distName} ജില്ല</td>\n</tr>\n";
        foreach ($rows as $r) {
            $constName = htmlspecialchars($r['const_name']);

            if ($r['candidate_name']) {
                $color = htmlspecialchars($r['alliance_color'] ?? '#757575');
                $allianceLower = strtolower(trim($r['alliance_name'] ?? ''));
                if ($allianceLower === 'ldf') $allianceClass = 'party-ldf';
                elseif ($allianceLower === 'udf') $allianceClass = 'party-udf';
                elseif ($allianceLower === 'nda') $allianceClass = 'party-nda';
                else $allianceClass = 'party-others';

                if ($r['status'] === 'won') {
                    $statusHtml = '<span class="status-won">' . (int)$r['lead_count'] . ' വോട്ടിന് വിജയിച്ചു</span>';
                } else {
                    $statusHtml = '<span class="status-leading">' . (int)$r['lead_count'] . ' വോട്ടുകൾക്ക് മുന്നിൽ</span>';
                }
                $candName = htmlspecialchars($r['candidate_name']);
                $partyName = htmlspecialchars($r['party_name']);
                $candName = "{$candName} ({$partyName})";
                $logo = htmlspecialchars($r['party_logo'] ?? '');
                $logoHtml = $logo ? "<img src=\"{$logo}\" alt=\"{$partyName}\" class=\"party-logo\"> " : '';
                $allianceName = htmlspecialchars($r['alliance_name'] ?? 'Others');
                $partyHtml = "{$logoHtml}<span class=\"party-badge {$allianceClass}\" style=\"background:{$color}\">{$allianceName}</span>";
            } else {
                $candName = '<span style="color:#999;">—</span>';
                $partyHtml = '<span style="color:#999;">—</span>';
                $statusHtml = '<span class="">-</span>';
            }

            $html .= " \n<tr>\n";
            $html .= "<td data-label=\"മണ്ഡലം\" class=\"title normal_title\">{$constName}</td>\n";
            $html .= "<td data-label=\"സ്ഥാനാർത്ഥി\" class=\"title normal_title\">{$candName}</td>\n";
            $html .= "<td data-label=\"പാർട്ടി\" class=\"title normal_title\">{$partyHtml}</td>\n";
            $html .= "<td data-label=\"സ്ഥിതി\">{$statusHtml}</td>\n";
            $html .= "</tr>\n";
        }
    }
    $html .= " \n</tbody>\n</table>\n";
    file_put_contents(__DIR__ . '/electionresult.html', $html);
    $key = "8fK2vP9mN4qR7wL1bX5jV0cA3yE6tI8oU9bN4qR7wL1bX5jV0cA3yE6tI8oU9bN4qR";
    $timestamp = time(); // current Unix timestamp
    
    $url = "https://janayugomonline.com/electionupdater.php?key=$key&ts=$timestamp";
    
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    
    if (curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    } else {
        echo $response;
    }
    
    curl_close($ch);
}

// Fetch districts into array
$districtResult = $conn->query("SELECT id, name FROM ref_districts ORDER BY id");
$allDistricts = [];
while ($d = $districtResult->fetch_assoc()) {
    $allDistricts[] = $d;
}

// Fetch all constituencies
$constituencies = $conn->query("SELECT id, name, district_id, winner_candidate_id, lead_count, status FROM constituency ORDER BY id");
$constByDistrict = [];
while ($row = $constituencies->fetch_assoc()) {
    $constByDistrict[$row['district_id']][] = $row;
}

// Fetch all candidates grouped by constituency
$candidates = $conn->query("SELECT c.id, c.name, c.constituency_id, c.votes, p.name AS party_name, a.name AS alliance_name FROM candidates c LEFT JOIN party p ON c.party_id = p.id LEFT JOIN alliance a ON c.alliance_id = a.id ORDER BY c.name");
$candByConst = [];
while ($row = $candidates->fetch_assoc()) {
    $candByConst[$row['constituency_id']][] = $row;
}

$savedId = isset($_SESSION['saved_id']) ? (int)$_SESSION['saved_id'] : 0;
unset($_SESSION['saved_id']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Election Results</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: Arial, sans-serif; background: #f0f2f5; padding: 20px; }
        h1 { text-align: center; margin-bottom: 20px; color: #333; }
        .district { background: #fff; border-radius: 8px; margin-bottom: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); overflow: hidden; }
        .district-header { background: #2c3e50; color: #fff; padding: 12px 20px; font-size: 18px; font-weight: bold; display: flex; justify-content: space-between; align-items: center; }
        .district-search { padding: 6px 10px; border: none; border-radius: 4px; font-size: 13px; width: 220px; outline: none; }
        table { width: 100%; border-collapse: collapse; }
        th { background: #ecf0f1; padding: 10px 12px; text-align: left; font-size: 13px; color: #555; border-bottom: 2px solid #ddd; }
        td { padding: 8px 12px; border-bottom: 1px solid #eee; vertical-align: middle; }
        tr:hover { background: #f9f9f9; }
        select, input[type="number"] { padding: 6px 8px; border: 1px solid #ccc; border-radius: 4px; font-size: 13px; }
        select { min-width: 180px; }
        input[type="number"] { width: 100px; }
        .btn-save { background: #27ae60; color: #fff; border: none; padding: 7px 16px; border-radius: 4px; cursor: pointer; font-size: 13px; }
        .btn-save:hover { background: #219a52; }
        .saved-msg { color: #27ae60; font-size: 12px; font-weight: bold; margin-left: 8px; }
        .const-name { font-weight: bold; white-space: nowrap; }
        .alliance-cell { font-size: 12px; font-weight: bold; }
        .alliance-ldf { color: #c62828; }
        .alliance-udf { color: #1565c0; }
        .alliance-nda { color: #e65100; }
        .alliance-others { color: #9e9e9e; }
        .district-tags { display:flex; flex-wrap:wrap; gap:8px; margin-bottom:20px; justify-content:center; }
        .district-tag { display:inline-flex; align-items:center; gap:6px; background:#2c3e50; color:#fff; padding:7px 14px; border-radius:20px; font-size:13px; font-weight:600; text-decoration:none; cursor:pointer; transition:background 0.2s; }
        .district-tag:hover { background:#1a252f; }
        .district-tag-count { background:rgba(255,255,255,0.25); padding:2px 8px; border-radius:12px; font-size:12px; font-weight:700; min-width:22px; text-align:center; }
    </style>
</head>
<body>
    <h1>Election Results Management</h1>

    <div class="district-tags">
    <?php foreach ($allDistricts as $dt):
        $dtCount = count($constByDistrict[$dt['id']] ?? []);
    ?>
        <a href="javascript:void(0);" class="district-tag" onclick="scrollToDistrict('admin-district-<?= $dt['id'] ?>')"><?= htmlspecialchars($dt['name']) ?> <span class="district-tag-count"><?= $dtCount ?></span></a>
    <?php endforeach; ?>
    </div>

    <?php foreach ($allDistricts as $district): ?>
    <div class="district" id="admin-district-<?= $district['id'] ?>">
        <div class="district-header">
            <span><?= htmlspecialchars($district['name']) ?></span>
            
        </div>
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Constituency</th>
                    <th>Candidate</th>
                    <th>Lead Count</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $consts = $constByDistrict[$district['id']] ?? [];
                $sn = 1;
                foreach ($consts as $c):
                    $cands = $candByConst[$c['id']] ?? [];
                ?>
                <tr>
                    <form method="POST" onsubmit="return validateForm(this)">
                        <input type="hidden" name="constituency_id" value="<?= $c['id'] ?>">
                        <td><?= $sn++ ?></td>
                        <td class="const-name"><?= htmlspecialchars($c['name']) ?></td>
                        <td>
                            <select name="winner_candidate_id" required onchange="updateAlliance(this, <?= $c['id'] ?>)">
                                <option value="">-- Select --</option>
                                <?php foreach ($cands as $cand): ?>
                                <option value="<?= $cand['id'] ?>" data-alliance="<?= htmlspecialchars($cand['alliance_name'] ?? 'Others') ?>" <?= ($c['winner_candidate_id'] == $cand['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($cand['name']) ?> (<?= htmlspecialchars($cand['party_name'] ?? 'IND') ?> - <?= htmlspecialchars($cand['alliance_name'] ?? 'Others') ?>)
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                        <?php
                            $winnerVotes = 0;
                            $winnerAlliance = '';
                            if ($c['winner_candidate_id']) {
                                foreach ($cands as $cd) {
                                    if ($cd['id'] == $c['winner_candidate_id']) {
                                        $winnerVotes = (int)$cd['votes'];
                                        $winnerAlliance = $cd['alliance_name'] ?? 'Others';
                                        break;
                                    }
                                }
                            }
                        ?>
                        <td><input type="number" name="lead_count" value="<?= (int)$c['lead_count'] ?>" min="1" required></td>
                        <td>
                            <select name="status" required>
                                <option value="leading" <?= ($c['status'] !== 'won') ? 'selected' : '' ?>>Leading</option>
                                <option value="won" <?= ($c['status'] === 'won') ? 'selected' : '' ?>>Won</option>
                            </select>
                        </td>
                        <td>
                            <button type="submit" class="btn-save">Save</button>
                            <?php if ($savedId === (int)$c['id']): ?>
                                <span class="saved-msg">Saved!</span>
                            <?php endif; ?>
                        </td>
                    </form>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endforeach; ?>

<script>
function validateForm(form) {
    if (!form.winner_candidate_id.value) { alert('Please select a candidate'); return false; }
    if (!form.lead_count.value || parseInt(form.lead_count.value) <= 0) { alert('Lead count must be greater than 0'); return false; }
    if (!form.status.value) { alert('Please select a status'); return false; }
    return true;
}
function updateAlliance(select, constId) {
    var cell = document.getElementById('alliance-' + constId);
    var option = select.options[select.selectedIndex];
    var alliance = option ? (option.getAttribute('data-alliance') || '') : '';
    cell.textContent = alliance;
    cell.className = 'alliance-cell';
    var key = alliance.toLowerCase().replace(/[^a-z]/g, '');
    if (key === 'ldf') cell.classList.add('alliance-ldf');
    else if (key === 'udf') cell.classList.add('alliance-udf');
    else if (key === 'nda') cell.classList.add('alliance-nda');
    else cell.classList.add('alliance-others');
}
function scrollToDistrict(id) {
    var el = document.getElementById(id);
    if (el) { el.scrollIntoView({behavior:'smooth', block:'start'}); }
}
function filterRows(input) {
    const query = input.value.toLowerCase();
    const table = input.closest('.district').querySelector('tbody');
    const rows = table.querySelectorAll('tr');
    rows.forEach(row => {
        const name = row.querySelector('.const-name');
        if (name) {
            row.style.display = name.textContent.toLowerCase().includes(query) ? '' : 'none';
        }
    });
}
</script>
</body>
</html>
<?php $conn->close(); ?>