<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../lib/auth.php';
require_once __DIR__ . '/../../lib/csrf.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

requireLogin();

$pageTitle = 'Crop Cards';
$siteName  = 'Crop Monitor';

$pdo    = getDBConnection();
$userId = getCurrentUserId();

// ── Block counts for sidebar badges ──────────────────────────────────────────
$stmtArchived = $pdo->prepare(
    'SELECT COUNT(*) FROM block_info WHERE modx_user_id = ? AND status = 2'
);
$stmtArchived->execute([$userId]);
$archivedCount = (int) $stmtArchived->fetchColumn();

$stmtDeleted = $pdo->prepare(
    'SELECT COUNT(*) FROM block_info WHERE modx_user_id = ? AND status = 3'
);
$stmtDeleted->execute([$userId]);
$deletedCount = (int) $stmtDeleted->fetchColumn();

// ── Block list (status 0 = new, 1 = active) ───────────────────────────────
$stmtBlocks = $pdo->prepare(
    'SELECT * FROM block_info WHERE modx_user_id = ? AND status <= 1 ORDER BY id ASC'
);
$stmtBlocks->execute([$userId]);
$blocks = $stmtBlocks->fetchAll();

// ── Flash messages ────────────────────────────────────────────────────────
$flashSuccess = $_SESSION['flash_success'] ?? null;
$flashError   = $_SESSION['flash_error']   ?? null;
unset($_SESSION['flash_success'], $_SESSION['flash_error']);

$h = fn($v) => htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8');

include __DIR__ . '/../../layouts/header.php';
include __DIR__ . '/../../layouts/navbar.php';
?>

<div id="layoutSidenav">
    <div id="layoutSidenav_nav">
        <?php include __DIR__ . '/../../layouts/sidebar.php'; ?>
    </div>
    <div id="layoutSidenav_content">
        <main>
            <div class="container-fluid px-4">

                <h1 class="mt-4"><?= $h($pageTitle) ?></h1>
                <ol class="breadcrumb mb-4">
                    <li class="breadcrumb-item"><a href="/dashboard/dashboard.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Crop Cards</li>
                </ol>

                <?php if ($flashSuccess): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?= $h($flashSuccess) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                <?php if ($flashError): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?= $h($flashError) ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <div class="row">

                    <!-- ── Left sidebar panel ──────────────────────────────── -->
                    <div class="col-12 col-md-3">

                        <div class="row mb-3">
                            <div class="col">
                                <form action="" method="GET">
                                    <div class="input-group">
                                        <input type="text" class="form-control" name="q"
                                               placeholder="Search..."
                                               value="<?= $h($_GET['q'] ?? '') ?>">
                                        <span class="input-group-text"><i class="fa fa-search"></i></span>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col">
                                <div class="alert alert-danger">
                                    <h5 class="mb-0"><?= $h($pageTitle) ?></h5>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col">
                                <div class="list-group">
                                    <a href="#" class="list-group-item list-group-item-action fw-bold">
                                        Folders
                                    </a>
                                    <a href="#" class="list-group-item list-group-item-action list-group-item-light text-warning">
                                        <i class="fa fa-archive text-warning"></i> Archived
                                        <span class="badge bg-warning text-dark float-end"><?= $archivedCount ?></span>
                                    </a>
                                    <a href="#" class="list-group-item list-group-item-action list-group-item-light text-danger">
                                        <i class="fa fa-trash text-danger"></i> Deleted
                                        <span class="badge bg-danger float-end"><?= $deletedCount ?></span>
                                    </a>
                                </div>
                            </div>
                        </div>

                    </div><!-- /col: left panel -->

                    <!-- ── Block list ───────────────────────────────────────── -->
                    <div class="col-12 col-md-9">

                        <div class="row mb-3">
                            <div class="col">
                                <button type="button" class="btn btn-success"
                                        data-bs-toggle="modal" data-bs-target="#createPaddock">
                                    <i class="fas fa-plus me-1"></i>Create New Paddock
                                </button>
                            </div>
                        </div>

                        <!-- Column headers (desktop only) -->
                        <div class="d-none d-md-block mb-1">
                            <div class="row fw-bold text-center text-muted small">
                                <div class="col-md-1">ID</div>
                                <div class="col-md-2">Block</div>
                                <div class="col">Name</div>
                                <div class="col-md-1">Size</div>
                                <div class="col-md-2">Location</div>
                                <div class="col-md-2">Current Crop</div>
                                <div class="col-md-1">Status</div>
                                <div class="col-md-1">Actions</div>
                            </div>
                        </div>

                        <?php if (empty($blocks)): ?>
                            <div class="alert alert-info">No paddock records found. Create your first paddock above.</div>
                        <?php endif; ?>

                        <?php foreach ($blocks as $i => $row):
                            $rowid    = (int) $row['id'];
                            $areaHa   = number_format((float) $row['area'], 1);
                            $areaAc   = number_format((float) $row['area'] * 2.47105, 1);
                            $areaDisp = $areaHa . ' ha – ' . $areaAc . ' ac';
                        ?>
                        <div class="row mb-2">
                            <div class="col border border-success rounded p-2">
                                <div class="row align-items-center">
                                    <div class="col-md-1 text-center fw-bold"><?= $i + 1 ?></div>
                                    <div class="col-6 col-sm-11 col-md-2">
                                        <div class="row g-1">
                                            <div class="col-6">
                                                <a class="btn btn-primary btn-sm w-100"
                                                   href="/dashboard/crop-cards/block-detail.php?rid=<?= $rowid ?>&id=<?= $h($row['block_id']) ?>&block=<?= urlencode($row['name'] ?? '') ?>"
                                                   title="View block">
                                                    <i class="fas fa-globe-asia text-white"></i>
                                                </a>
                                            </div>
                                            <div class="col-6">
                                                <button type="button"
                                                        class="btn btn-success btn-sm w-100"
                                                        data-bs-toggle="modal"
                                                        data-bs-target="#editPaddock<?= $rowid ?>">
                                                    <i class="far fa-edit"></i> <?= $h($row['block_id']) ?>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col">
                                        <label class="form-label form-label-sm mb-0 d-block d-sm-none">Name</label>
                                        <input type="text" class="form-control form-control-sm"
                                               value="<?= $h($row['name']) ?>" readonly>
                                    </div>
                                    <div class="col-md-1">
                                        <label class="form-label form-label-sm mb-0 d-block d-sm-none">Size</label>
                                        <input type="text" class="form-control form-control-sm text-center"
                                               value="<?= $h($areaDisp) ?>" readonly>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label form-label-sm mb-0 d-block d-sm-none">Location</label>
                                        <input type="text" class="form-control form-control-sm"
                                               value="<?= $h($row['location']) ?>" readonly>
                                    </div>
                                    <div class="col-md-2">
                                        <label class="form-label form-label-sm mb-0 d-block d-sm-none">Current Crop</label>
                                        <input type="text" class="form-control form-control-sm" value="" readonly>
                                    </div>
                                    <div class="col-md-1">
                                        <label class="form-label form-label-sm mb-0 d-block d-sm-none">Status</label>
                                        <input type="text" class="form-control form-control-plaintext form-control-sm text-center"
                                               value="<?= $h($row['status']) ?>" readonly>
                                    </div>
                                    <div class="col-md-1">
                                        <label class="form-label form-label-sm mb-0 d-block d-sm-none">Actions</label>
                                        <a href="#" title="Delete Block"><i class="fa fa-trash text-danger"></i></a>&nbsp;
                                        <a href="#" title="Archive Block"><i class="fa fa-archive text-warning"></i></a>&nbsp;
                                        <a href="#" title="Reply to Client"><i class="fa fa-reply text-success"></i></a>&nbsp;
                                        <a href="#" title="Share Report"><i class="fa fa-share text-success"></i></a>&nbsp;
                                        <a href="#" title="Download Report"><i class="fas fa-cloud-download-alt text-dark"></i></a>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Edit Paddock modal -->
                        <div class="modal fade" id="editPaddock<?= $rowid ?>" tabindex="-1"
                             aria-labelledby="editPaddock<?= $rowid ?>Label" aria-hidden="true">
                            <div class="modal-dialog modal-lg modal-dialog-centered">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="editPaddock<?= $rowid ?>Label">
                                            Edit Paddock — <?= $h($row['name']) ?>
                                        </h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <form method="post" action="/controllers/blockSubmit.php"
                                          id="editPaddockForm<?= $rowid ?>">
                                        <div class="modal-body">
                                            <input type="hidden" name="csrf_token"
                                                   value="<?= $h(generateCsrfToken()) ?>">
                                            <input type="hidden" name="action"    value="edit">
                                            <input type="hidden" name="record_id" value="<?= $rowid ?>">

                                            <div class="row mb-3">
                                                <div class="col">
                                                    <label class="form-label">Block ID</label>
                                                    <input type="text" class="form-control form-control-sm"
                                                           name="block_id" value="<?= $h($row['block_id']) ?>" required>
                                                </div>
                                                <div class="col">
                                                    <label class="form-label">Block Name</label>
                                                    <input type="text" class="form-control form-control-sm"
                                                           name="name" value="<?= $h($row['name']) ?>" required>
                                                </div>
                                            </div>

                                            <hr>
                                            <h6>Location / Sizing</h6>

                                            <div class="mb-3">
                                                <label class="form-label">Location</label>
                                                <input type="text" class="form-control form-control-sm"
                                                       name="location" value="<?= $h($row['location']) ?>">
                                            </div>

                                            <div class="row mb-3">
                                                <div class="col">
                                                    <label class="form-label">Area (hectares)</label>
                                                    <input type="number" step="0.01" class="form-control form-control-sm"
                                                           id="edit_area_ha_<?= $rowid ?>" name="area_ha"
                                                           value="<?= $h(number_format((float) $row['area'], 2)) ?>"
                                                           oninput="areaConverter('area_ha',this.value,'<?= $rowid ?>')">
                                                    <div class="form-text">in hectares</div>
                                                </div>
                                                <div class="col">
                                                    <label class="form-label">Area (acres)</label>
                                                    <input type="number" step="0.01" class="form-control form-control-sm"
                                                           id="edit_area_ac_<?= $rowid ?>"
                                                           value="<?= $h(number_format((float) $row['area'] * 2.47105, 2)) ?>"
                                                           oninput="areaConverter('area_ac',this.value,'<?= $rowid ?>')">
                                                    <div class="form-text">in acres</div>
                                                </div>
                                                <div class="col">
                                                    <label class="form-label">GPS</label>
                                                    <input type="text" class="form-control form-control-sm"
                                                           name="gps" value="<?= $h($row['gps']) ?>">
                                                </div>
                                            </div>

                                            <hr>
                                            <h6>Soil Classification</h6>
                                            <div class="row">
                                                <div class="col">
                                                    <label class="form-label">Soil Type</label>
                                                    <select class="form-select form-select-sm" name="analysis_type">
                                                        <option value="">Select soil type...</option>
                                                        <option value="sandy">Sandy</option>
                                                        <option value="light">Light</option>
                                                        <option value="medium">Medium</option>
                                                        <option value="heavy">Heavy</option>
                                                    </select>
                                                </div>
                                            </div>

                                        </div><!-- /modal-body -->
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                            <button type="submit" class="btn btn-success">Save Changes</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div><!-- /editPaddock modal -->

                        <?php endforeach; ?>

                    </div><!-- /col: block list -->

                </div><!-- /row: main content -->

                <!-- ── Crop Information summary (placeholder) ─────────────── -->
                <div class="container-fluid mt-4">
                    <div class="row mb-3">
                        <div class="col">
                            <div class="card border-success">
                                <div class="card-body py-2">
                                    <div class="row">
                                        <div class="col-3">
                                            <label class="form-label small mb-0">Farm Name</label>
                                            <input type="text" class="form-control form-control-sm" readonly>
                                        </div>
                                        <div class="col-3">
                                            <label class="form-label small mb-0">Paddock Name</label>
                                            <input type="text" class="form-control form-control-sm" readonly>
                                        </div>
                                        <div class="col-3">
                                            <label class="form-label small mb-0">Crop Name</label>
                                            <input type="text" class="form-control form-control-sm" readonly>
                                        </div>
                                        <div class="col-3">
                                            <label class="form-label small mb-0">Area</label>
                                            <input type="text" class="form-control form-control-sm" readonly>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <h4>Crop Information</h4>

                    <div class="row">
                        <div class="col-4">
                            <div class="card">
                                <div class="card-header"><h5 class="mb-0">Current Alerts</h5></div>
                                <div class="card-body p-0">
                                    <table class="table table-striped table-hover mb-0">
                                        <thead class="table-danger">
                                            <tr><th>#</th><th>Alert</th><th>Level</th></tr>
                                        </thead>
                                        <tbody>
                                            <tr><td colspan="3" class="text-muted text-center">No alerts</td></tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="card">
                                <div class="card-header"><h5 class="mb-0">Fertiliser &amp; Disease Control</h5></div>
                                <div class="card-body p-0">
                                    <table class="table table-striped table-hover mb-0">
                                        <thead class="table-success">
                                            <tr><th>#</th><th>Product</th><th>Date</th></tr>
                                        </thead>
                                        <tbody>
                                            <tr><td colspan="3" class="text-muted text-center">No records</td></tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="col-4">
                            <div class="card">
                                <div class="card-header"><h5 class="mb-0">Irrigation &amp; Weather</h5></div>
                                <div class="card-body p-0">
                                    <table class="table table-striped table-hover mb-0">
                                        <thead class="table-warning">
                                            <tr><th>#</th><th>Event</th><th>Date</th></tr>
                                        </thead>
                                        <tbody>
                                            <tr><td colspan="3" class="text-muted text-center">No records</td></tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div><!-- /crop information -->

            </div><!-- /container-fluid -->

        </main>

        <!-- ── Create New Paddock modal ──────────────────────────────────────── -->
        <div class="modal fade" id="createPaddock" tabindex="-1"
             aria-labelledby="createPaddockLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="createPaddockLabel">Create Paddock Record</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <form method="post" action="/controllers/blockSubmit.php" id="createPaddockForm">
                        <div class="modal-body">
                            <input type="hidden" name="csrf_token"
                                   value="<?= $h(generateCsrfToken()) ?>">
                            <input type="hidden" name="action" value="create">

                            <h6>Block Identification</h6>
                            <div class="row mb-3">
                                <div class="col">
                                    <label class="form-label">Block ID</label>
                                    <input type="text" class="form-control form-control-sm"
                                           name="block_id" placeholder="e.g. BLK-001" required>
                                </div>
                                <div class="col">
                                    <label class="form-label">Block Name</label>
                                    <input type="text" class="form-control form-control-sm"
                                           name="name" placeholder="e.g. North Paddock" required>
                                </div>
                            </div>

                            <hr>
                            <h6>Location / Sizing</h6>

                            <div class="mb-3">
                                <label class="form-label">Location / Address</label>
                                <input type="text" class="form-control form-control-sm"
                                       name="location" placeholder="Block address">
                            </div>

                            <div class="row mb-3">
                                <div class="col">
                                    <label class="form-label">Area (hectares)</label>
                                    <input type="number" step="0.01" class="form-control form-control-sm"
                                           id="create_area_ha" name="area_ha" placeholder="0.00"
                                           oninput="areaConverter('area_ha',this.value,'create')">
                                    <div class="form-text">in hectares</div>
                                </div>
                                <div class="col">
                                    <label class="form-label">Area (acres)</label>
                                    <input type="number" step="0.01" class="form-control form-control-sm"
                                           id="create_area_ac" placeholder="0.00"
                                           oninput="areaConverter('area_ac',this.value,'create')">
                                    <div class="form-text">in acres</div>
                                </div>
                                <div class="col">
                                    <label class="form-label">GPS Coordinates</label>
                                    <input type="text" class="form-control form-control-sm"
                                           name="gps" placeholder="e.g. -33.8688, 151.2093">
                                </div>
                            </div>

                            <hr>
                            <h6>Soil Classification</h6>
                            <div class="row">
                                <div class="col">
                                    <label class="form-label">Soil Type</label>
                                    <select class="form-select form-select-sm" name="analysis_type">
                                        <option value="">Select soil type...</option>
                                        <option value="sandy">Sandy</option>
                                        <option value="light">Light</option>
                                        <option value="medium">Medium</option>
                                        <option value="heavy">Heavy</option>
                                    </select>
                                </div>
                            </div>

                        </div><!-- /modal-body -->
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-success">Create Paddock</button>
                        </div>
                    </form>
                </div>
            </div>
        </div><!-- /createPaddock modal -->

<?php include __DIR__ . '/../../layouts/footer.php'; ?>

<script>
/**
 * Convert between hectares and acres in Create and Edit paddock modals.
 * suffix: 'create' for the create modal, or the rowid for edit modals.
 */
function areaConverter(source, valNum, suffix) {
    valNum = parseFloat(valNum) || 0;
    var haId = (suffix === 'create') ? 'create_area_ha' : 'edit_area_ha_' + suffix;
    var acId = (suffix === 'create') ? 'create_area_ac' : 'edit_area_ac_' + suffix;
    var haEl = document.getElementById(haId);
    var acEl = document.getElementById(acId);
    if (!haEl || !acEl) return;

    if (source === 'area_ha') {
        acEl.value = (valNum / 0.404686).toFixed(2);
    } else {
        haEl.value = (valNum / 2.47105).toFixed(2);
    }
}
</script>
