<?php
session_start();

set_exception_handler(function ($e) {
    echo '<div style="margin:20px;padding:16px;background:#f8d7da;color:#721c24;'
       . 'border:1px solid #f5c6cb;border-radius:6px;font-family:monospace;">'
       . '<strong>Fatal error:</strong> ' . htmlspecialchars($e->getMessage())
       . '<br><small>' . htmlspecialchars($e->getFile()) . ':' . $e->getLine() . '</small>'
       . '</div>';
});
register_shutdown_function(function () {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        echo '<div style="margin:20px;padding:16px;background:#f8d7da;color:#721c24;'
           . 'border:1px solid #f5c6cb;border-radius:6px;font-family:monospace;">'
           . '<strong>Fatal error:</strong> ' . htmlspecialchars($err['message'])
           . '<br><small>' . htmlspecialchars($err['file']) . ':' . $err['line'] . '</small>'
           . '</div>';
    }
});



$view       = isset($_REQUEST['view']) && $_REQUEST['view'] == 'list' ? 'list' : 'grid';
$sel_date   = isset($_REQUEST['date']) && $_REQUEST['date'] ? $_REQUEST['date'] : date('Y-m-d');
$sel_date   = date('Y-m-d', strtotime($sel_date));
$page_header = "Replica Wood Planning";
$current_page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 'replica_wood_production';

$sql_errors = [];

function rw_resolve_color_id_by_name($conn, $name) {
    $name = mysqli_real_escape_string($conn, $name);
    $res = mysqli_query($conn, "SELECT id FROM keycode WHERE name='color_rep_wood' AND LOWER(code)=LOWER('$name') LIMIT 1");
    return ($res && mysqli_num_rows($res) > 0) ? (int) mysqli_fetch_assoc($res)['id'] : 0;
}

$FIXED_LINE_COLOURS = [1 => 'Black', 2 => 'Rosewood', 3 => 'Golden Oak', 4 => 'Anth Grey'];

$all_colors = [];
$col_res = mysqli_query($conn, "SELECT id, code FROM keycode WHERE name = 'color_rep_wood' ORDER BY ord ASC");
if ($col_res) {
    while ($row = mysqli_fetch_assoc($col_res)) { $all_colors[] = $row; }
} else {
    $sql_errors[] = "Colour list lookup failed: " . mysqli_error($conn);
}

$bespoke_text = '';
$bes_date_esc = mysqli_real_escape_string($conn, $sel_date);
$bes_res = mysqli_query($conn, "SELECT color_text FROM replica_wood_bespoke_color WHERE req_date = '$bes_date_esc' LIMIT 1");
if ($bes_res && mysqli_num_rows($bes_res) > 0) {
    $bespoke_text = mysqli_fetch_assoc($bes_res)['color_text'];
}

$lines = [];
foreach ($FIXED_LINE_COLOURS as $slot => $colourName) {
    $lines[] = ['slot' => $slot, 'id' => rw_resolve_color_id_by_name($conn, $colourName), 'code' => $colourName, 'label' => "Line $slot"];
}
$lines[] = [
    'slot'  => 5,
    'id'    => rw_resolve_color_id_by_name($conn, 'Bespoke'),
    'code'  => $bespoke_text !== '' ? $bespoke_text : 'Not set for this date',
    'label' => 'Line 5',
];

$sizes = [];
$size_sql = "SELECT DISTINCT rep_wood_length AS size_val
             FROM item_management
             WHERE replica_wood = 1
               AND rep_wood_length IS NOT NULL
               AND rep_wood_length != ''
             ORDER BY CAST(rep_wood_length AS UNSIGNED) ASC, rep_wood_length ASC";
$size_res = mysqli_query($conn, $size_sql);
if ($size_res) {
    while ($row = mysqli_fetch_assoc($size_res)) {
        $sizes[] = $row['size_val'];
    }
} else {
    $sql_errors[] = "Size lookup failed: " . mysqli_error($conn);
}

function rw_get_item($conn, $line_id, $size) {
    if ($line_id <= 0) return null;
    $size = mysqli_real_escape_string($conn, $size);
    $sql = "SELECT id, part_number, product_description
            FROM item_management
            WHERE replica_wood = 1
              AND color_rep_wood = " . intval($line_id) . "
              AND rep_wood_length = '$size'
            LIMIT 1";
    $res = mysqli_query($conn, $sql);
    return ($res && mysqli_num_rows($res) > 0) ? mysqli_fetch_assoc($res) : null;
}

function rw_get_current_qty($conn, $part_id, $date) {
    $date = mysqli_real_escape_string($conn, $date);
    $sql = "SELECT req_qty FROM replica_wood_planning
            WHERE part_id = " . intval($part_id) . " AND req_date = '$date' LIMIT 1";
    $res = mysqli_query($conn, $sql);
    if ($res && mysqli_num_rows($res) > 0) {
        return (int) mysqli_fetch_assoc($res)['req_qty'];
    }
    return 0;
}

function rw_get_arrears($conn, $part_id, $date) {
    $date = mysqli_real_escape_string($conn, $date);
    $sql = "SELECT SUM(GREATEST(p.req_qty - COALESCE(c.quantity, 0), 0)) AS total
            FROM replica_wood_planning p
            LEFT JOIN replica_wood_count_log c
                ON c.part_id = p.part_id AND c.req_date = p.req_date
            WHERE p.part_id = " . intval($part_id) . "
              AND p.req_date < '$date'";
    $res = mysqli_query($conn, $sql);
    if (!$res) return 0;
    $row = mysqli_fetch_assoc($res);
    $total = (int) ($row['total'] ?? 0);
    return $total > 0 ? $total : 0;
}

$grid = [];
$grand_total = 0;

foreach ($lines as $line) {
    foreach ($sizes as $size) {
        $item = rw_get_item($conn, $line['id'], $size);
        if (!$item) {
            $grid[$line['slot']][$size] = null;
            continue;
        }
        $current = rw_get_current_qty($conn, $item['id'], $sel_date);
        $arrears = rw_get_arrears($conn, $item['id'], $sel_date);

        $grid[$line['slot']][$size] = [
            'item'    => $item,
            'current' => $current,
            'arrears' => $arrears,
        ];
        $grand_total += $current + $arrears;
    }
}

$line_rgb = ['26,26,26', '122,31,43', '184,128,20', '74,74,74', '142,109,196'];
function rw_line_rgb($index, $line_rgb) {
    return $line_rgb[$index % count($line_rgb)];
}
?>

<section class="content-header">
    <h1><?= $page_header; ?></h1>
</section>

<style>
:root{
    --rw-save:#14818f;
    --rw-save-dark:#0f6b77;
    --rw-ink:#20232a;
    --rw-muted:#6b7280;
    --rw-border:#e5e7eb;
    --rw-bg:#f6f7f9;
    --rw-radius:10px;
}
.rw-toolbar{
    display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:12px;
    margin-bottom:14px;padding-bottom:14px;border-bottom:1px solid var(--rw-border);
}
.rw-toolbar-left{display:flex;align-items:center;gap:16px;flex-wrap:wrap;}
.rw-toolbar form{display:flex;align-items:center;gap:10px;}
.rw-toolbar label{margin:0;font-size:13px;font-weight:600;color:var(--rw-muted);text-transform:uppercase;letter-spacing:.03em;}
.rw-toolbar input[type=date]{border:1px solid var(--rw-border);border-radius:8px;padding:7px 10px;font-size:14px;}
.rw-view-toggle{display:inline-flex;background:var(--rw-bg);border-radius:8px;padding:3px;gap:2px;}
.rw-view-toggle a{
    padding:7px 16px;border-radius:6px;font-size:13px;font-weight:600;text-decoration:none;color:var(--rw-muted);
    transition:all .15s ease;
}
.rw-view-toggle a.active{background:#fff;color:var(--rw-ink);box-shadow:0 1px 3px rgba(0,0,0,.12);}
.rw-view-toggle a:not(.active):hover{color:var(--rw-ink);}

.rw-bespoke-picker{display:flex;align-items:center;gap:8px;background:#f5f0fa;border:1px solid #e3d7f0;border-radius:8px;padding:6px 10px;}
.rw-bespoke-picker input[type=text]{border:1px solid var(--rw-border);border-radius:6px;padding:6px 8px;font-size:13px;width:150px;}
.rw-bespoke-picker input[type=text]:focus{outline:none;border-color:#8e6dc4;}
.rw-bespoke-save-btn{background:#8e6dc4;color:#fff;border:none;border-radius:6px;padding:6px 12px;font-weight:700;font-size:12px;cursor:pointer;}
.rw-bespoke-save-btn:hover{background:#7a58ae;}
.rw-bespoke-save-btn:disabled{opacity:.6;cursor:not-allowed;}

.rw-grid-wrap{display:flex;gap:10px;overflow-x:auto;padding-bottom:8px;-webkit-overflow-scrolling:touch;}
.rw-grid-col{flex:1 0 150px;min-width:150px;}
.rw-line-header{
    color:#fff;font-weight:700;text-align:center;padding:9px 8px;border-radius:8px;
    font-size:13px;margin-bottom:8px;
}
.rw-line-header .rw-line-sub{
    display:block;font-size:15px;font-weight:600;opacity:.85;margin-top:2px;
    overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
}

.rw-cell{border-radius:14px;overflow:hidden;margin-bottom:8px;}
.rw-cell-top{display:flex;justify-content:space-between;align-items:flex-start;padding:12px 14px 14px;}
.rw-size{font-weight:800;font-size:26px;line-height:1;color:#fff;}
.rw-size.inactive-text{color:var(--rw-muted);}

.rw-arrears-block{display:flex;flex-direction:column;align-items:flex-end;gap:4px;}
.rw-arrears-label{color:#fff;font-weight:700;font-size:12px;line-height:1;}
.rw-arrears-box{
    background:#fff;border-radius:6px;min-width:56px;height:26px;padding:0 8px;
    display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:var(--rw-ink);
}

.rw-cell-bottom{background:#fff;display:flex;align-items:stretch;min-height:52px;}
.rw-qty-input{
    flex:1;min-width:0;border:none;background:transparent;text-align:center;
    font-size:15px;font-weight:800;color:#1c1d1f;outline:none;padding:0 8px;
}
.rw-qty-input:focus{color:var(--rw-ink);}
.rw-save-btn{
    flex:0 0 84px;background:var(--rw-save);color:#fff;border:none;
    font-weight:700;font-size:14px;cursor:pointer;transition:background .15s ease;
}
.rw-save-btn:hover{background:var(--rw-save-dark);}
.rw-save-btn:disabled{opacity:.6;cursor:not-allowed;}

.rw-footer-bar{display:grid;grid-template-columns:1fr auto 1fr;align-items:center;margin-top:16px;gap:10px;}
.rw-total-box{
    grid-column:2;justify-self:center;
    font-size:22px;font-weight:700;text-align:center;background:#fff;border:1px solid var(--rw-border);
    border-radius:var(--rw-radius);padding:12px 22px;min-width:110px;color:var(--rw-ink);
}
.rw-total-box small{display:block;font-size:11px;font-weight:600;color:var(--rw-muted);text-transform:uppercase;letter-spacing:.04em;margin-bottom:2px;}
.rw-clear-block{grid-column:3;justify-self:end;display:flex;align-items:center;gap:12px;flex-wrap:wrap;}
.rw-clear-btn{
    background:var(--rw-ink);color:#fff;border:none;border-radius:8px;padding:11px 20px;cursor:pointer;
    font-weight:600;font-size:13px;transition:background .15s ease;
}
.rw-clear-btn:hover{background:#000;}
.rw-clear-btn:disabled{opacity:.6;cursor:not-allowed;}
.rw-clear-note{color:#c0392b;font-size:12px;max-width:280px;line-height:1.4;}

.rw-table{width:100%;border-collapse:separate;border-spacing:0;font-size:13px;background:#fff;border-radius:var(--rw-radius);overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,.06);}
.rw-table thead th{
    background:var(--rw-bg);color:var(--rw-muted);text-transform:uppercase;font-size:11px;letter-spacing:.04em;
    font-weight:700;padding:10px 12px;text-align:left;border-bottom:1px solid var(--rw-border);
}
.rw-table tbody td{padding:10px 12px;border-bottom:1px solid var(--rw-border);vertical-align:middle;}
.rw-table tbody tr:last-child td{border-bottom:none;}
.rw-table tbody tr:hover{background:#fafafa;}
.rw-line-dot{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:7px;vertical-align:middle;}
.rw-table .rw-badge-arrears{background:var(--rw-bg);color:var(--rw-ink);border:1px solid var(--rw-border);border-radius:12px;padding:2px 9px;font-size:11px;font-weight:700;}
.rw-table input.rw-qty-input-row{width:100px;padding:6px 8px;border:1px solid var(--rw-border);border-radius:6px;font-size:13px;color:var(--rw-ink);}
.rw-table input.rw-qty-input-row:focus{outline:none;border-color:var(--rw-save);box-shadow:0 0 0 3px rgba(20,129,143,.15);}
.rw-table .btn-save-row{
    background:var(--rw-save);color:#fff;border:none;border-radius:6px;padding:6px 14px;font-weight:600;
    font-size:12px;cursor:pointer;transition:background .15s ease;
}
.rw-table .btn-save-row:hover{background:var(--rw-save-dark);}

.rw-alert{border-radius:var(--rw-radius);padding:14px 16px;margin-bottom:16px;font-size:13px;line-height:1.5;}
.rw-alert-danger{background:#fdecea;color:#a12b1f;border:1px solid #f4c7c1;}
.rw-alert-warning{background:#fff8e8;color:#8a6100;border:1px solid #f4e0a8;}
</style>

<section class="content">
    <div class="row">
        <div class="col-lg-12">
            <div class="rw-wrap">

                <?php if (isset($_SESSION['info_message'])) { ?>
                    <div class="alert alert-success alert-dismissable">
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                        <?= $_SESSION['info_message']; unset($_SESSION['info_message']); ?>
                    </div>
                <?php } ?>

                <?php if (!empty($sql_errors)) { ?>
                    <div class="rw-alert rw-alert-danger">
                        <strong>Replica Wood Planning could not load fully:</strong>
                        <ul style="margin:6px 0 0 18px;">
                            <?php foreach ($sql_errors as $err) { ?>
                                <li><?= htmlspecialchars($err); ?></li>
                            <?php } ?>
                        </ul>
                    </div>
                <?php } ?>

                <div class="box">
                    <div class="box-body">

                        <div class="rw-toolbar">
                            <div class="rw-toolbar-left">
                                <form method="GET">
                                    <input type="hidden" name="page" value="<?= htmlspecialchars($current_page); ?>">
                                    <input type="hidden" name="view" value="<?= $view; ?>">
                                    <label>Date</label>
                                    <input type="date" name="date" value="<?= $sel_date; ?>"
                                           onchange="this.form.submit()">
                                </form>

                                <div class="rw-bespoke-picker">
                                    <label style="text-transform:none;letter-spacing:0;">Bespoke colour (Line 5)</label>
                                    <input type="text" id="rwBespokeColorInput" list="rwBespokeColorSuggestions"
                                           placeholder="e.g. Ivory Oak" value="<?= htmlspecialchars($bespoke_text); ?>" autocomplete="off">
                                    
                                    <button type="button" id="rwSaveBespokeColor" class="rw-bespoke-save-btn">Save</button>
                                </div>
                            </div>

                            <div class="rw-view-toggle">
                                <a href="?page=<?= urlencode($current_page); ?>&view=grid&date=<?= $sel_date; ?>"
                                   class="<?= $view=='grid' ? 'active' : ''; ?>">Grid View</a>
                                <a href="?page=<?= urlencode($current_page); ?>&view=list&date=<?= $sel_date; ?>"
                                   class="<?= $view=='list' ? 'active' : ''; ?>">List View</a>
                            </div>
                        </div>

                        <?php if ($view === 'grid') { ?>
                            <div class="rw-grid-wrap">
                                <?php foreach ($lines as $li => $line):
                                    $rgb = rw_line_rgb($li, $line_rgb);
                                ?>
                                    <div class="rw-grid-col">
                                        <div class="rw-line-header" style="background:rgb(<?= $rgb; ?>);">
                                            <?= htmlspecialchars($line['label']); ?>
                                            <span class="rw-line-sub"><?= htmlspecialchars($line['code']); ?></span>
                                        </div>
                                        <?php foreach ($sizes as $size):
                                            $cell = $grid[$line['slot']][$size] ?? null;
                                            $has_item = $cell !== null;
                                            $bg_alpha = $has_item ? '1' : '0.09';
                                        ?>
                                            <div class="rw-cell">
                                                <div class="rw-cell-top" style="background:rgba(<?= $rgb; ?>,<?= $bg_alpha; ?>);">
                                                    <span class="rw-size <?= $has_item ? '' : 'inactive-text'; ?>"><?= htmlspecialchars($size); ?></span>
                                                    <span class="rw-arrears-block">
                                                        <span class="rw-arrears-label">Arrears</span>
                                                        <span class="rw-arrears-box"><?= ($has_item && $cell['arrears'] > 0) ? $cell['arrears'] : ''; ?></span>
                                                    </span>
                                                </div>
                                                <?php if ($has_item): ?>
                                                    <div class="rw-cell-bottom">
                                                        <input type="number" min="0" class="rw-qty-input"
                                                               id="rw_qty_<?= $cell['item']['id']; ?>"
                                                               value="<?= $cell['current'] > 0 ? $cell['current'] : ''; ?>"
                                                               placeholder="&mdash;">
                                                        <button type="button" class="rw-save-btn rw-save-btn-cell"
                                                                data-part-id="<?= $cell['item']['id']; ?>"
                                                                data-date="<?= $sel_date; ?>">Save</button>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endforeach; ?>
                            </div>

                            <div class="rw-footer-bar">
                                <div class="rw-total-box"><small>Total</small><?= $grand_total; ?></div>
                                <div class="rw-clear-block">
                                    <button type="button" id="rwClearAllArrears" class="rw-clear-btn">Clear Arrears</button>
                                    <span class="rw-clear-note">Clear arrears once they're factored into the requirement for the current or a future date.</span>
                                </div>
                            </div>

                        <?php } else { ?>
                            <div class="rw-clear-block" style="margin-bottom:16px;">
                                <button type="button" id="rwClearAllArrears" class="rw-clear-btn">Clear All Arrears</button>
                                <span class="rw-clear-note">Clear arrears once they're factored into the requirement for the current or a future date.</span>
                            </div>

                            <table class="rw-table">
                                <thead>
                                    <tr>
                                        <th>Line</th>
                                        <th>SKU / Size</th>
                                        <th>Arrears</th>
                                        <th>Current</th>
                                        <th>New Qty</th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($lines as $li => $line):
                                    $rgb = rw_line_rgb($li, $line_rgb);
                                ?>
                                    <?php foreach ($sizes as $size):
                                        $cell = $grid[$line['slot']][$size] ?? null;
                                        if (!$cell) continue;
                                    ?>
                                        <tr>
                                            <td>
                                                <span class="rw-line-dot" style="background:rgb(<?= $rgb; ?>);"></span>
                                                <?= htmlspecialchars($line['label']); ?> (<?= htmlspecialchars($line['code']); ?>)
                                            </td>
                                            <td><?= htmlspecialchars($size); ?></td>
                                            <td><?= $cell['arrears'] > 0 ? '<span class="rw-badge-arrears">' . $cell['arrears'] . '</span>' : '&mdash;'; ?></td>
                                            <td><?= $cell['current'] > 0 ? $cell['current'] : '&mdash;'; ?></td>
                                            <td>
                                                <input type="number" min="0" class="rw-qty-input-row"
                                                       id="rw_qty_<?= $cell['item']['id']; ?>" placeholder="Enter qty">
                                            </td>
                                            <td>
                                                <button type="button" class="btn-save-row rw-save-btn-cell"
                                                        data-part-id="<?= $cell['item']['id']; ?>"
                                                        data-date="<?= $sel_date; ?>">Save</button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php } ?>

                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).on('click', '.rw-save-btn-cell', function () {
    let $btn    = $(this);
    let partId  = $btn.data('part-id');
    let date    = $btn.data('date');
    let qtyRaw  = $('#rw_qty_' + partId).val();

    if (qtyRaw === '' || qtyRaw === null) {
        alert('Please enter a quantity (use 0 to clear the requirement).');
        return;
    }
    let qty = parseInt(qtyRaw, 10);
    if (isNaN(qty) || qty < 0) {
        alert('Please enter a valid quantity (0 or greater).');
        return;
    }

    $btn.prop('disabled', true).text('Saving...');

    $.ajax({
        url:  site_url + '/modules/production_planning/index.php?page=replica_wood_planning_ajax&action=save_requirement',
        type: 'POST',
        data: { part_id: partId, req_date: date, req_qty: qty },
        dataType: 'json',
        success: function (res) {
            if (res.status === 'success') {
                location.reload();
            } else {
                alert(res.message || 'Error saving requirement.');
                $btn.prop('disabled', false).text('Save');
            }
        },
        error: function () {
            alert('Something went wrong.');
            $btn.prop('disabled', false).text('Save');
        }
    });
});

$(document).on('click', '#rwClearAllArrears', function () {
    if (!confirm('Clear all outstanding arrears? This cannot be undone.')) return;
    let $btn = $(this);
    $btn.prop('disabled', true).text('Clearing...');

    $.ajax({
        url:  site_url + '/modules/production_planning/index.php?page=replica_wood_planning_ajax&action=clear_all_arrears',
        type: 'POST',
        data: { req_date: '<?= $sel_date; ?>' },
        dataType: 'json',
        success: function (res) {
            if (res.status === 'success') {
                location.reload();
            } else {
                alert(res.message || 'Error clearing arrears.');
                $btn.prop('disabled', false).text('Clear Arrears');
            }
        },
        error: function () {
            alert('Something went wrong.');
            $btn.prop('disabled', false).text('Clear Arrears');
        }
    });
});

$('#rwSaveBespokeColor').on('click', function () {
    let $btn      = $(this);
    let colorText = $('#rwBespokeColorInput').val().trim();

    if (!colorText) {
        alert('Please type a colour name for Line 5 (Bespoke) first.');
        return;
    }

    $btn.prop('disabled', true).text('Saving...');

    $.ajax({
        url:  site_url + '/modules/production_planning/index.php?page=replica_wood_planning_ajax&action=save_bespoke_color',
        type: 'POST',
        data: { req_date: '<?= $sel_date; ?>', color_text: colorText },
        dataType: 'json',
        success: function (res) {
            if (res.status === 'success') {
                location.reload();
            } else {
                alert(res.message || 'Error saving Bespoke colour.');
                $btn.prop('disabled', false).text('Save');
            }
        },
        error: function () {
            alert('Something went wrong.');
            $btn.prop('disabled', false).text('Save');
        }
    });
});
</script>