module spi_master_controller (
    input wire clk,
    input wire rst,
    input wire start,
    input wire [7:0] tx_data,
    input wire miso,
    output reg mosi,
    output reg sclk,
    output reg cs_n,
    output reg busy,
    output reg done,
    output reg [7:0] rx_data
);
    reg [7:0] tx_latched;
    reg [7:0] rx_shift;
    reg [2:0] bit_index;
    reg final_sample_seen;

    always @(posedge clk) begin
        done <= 1'b0;

        if (rst) begin
            mosi <= 1'b0;
            sclk <= 1'b0;
            cs_n <= 1'b1;
            busy <= 1'b0;
            rx_data <= 8'h00;
            tx_latched <= 8'h00;
            rx_shift <= 8'h00;
            bit_index <= 3'd0;
            final_sample_seen <= 1'b0;
        end else if (!busy) begin
            sclk <= 1'b0;
            cs_n <= 1'b1;
            final_sample_seen <= 1'b0;

            if (start) begin
                busy <= 1'b1;
                cs_n <= 1'b0;
                mosi <= tx_data[7];
                tx_latched <= tx_data;
                rx_shift <= 8'h00;
                bit_index <= 3'd7;
            end
        end else if (!sclk) begin
            sclk <= 1'b1;
            rx_shift[bit_index] <= miso;
            if (bit_index == 3'd0) begin
                final_sample_seen <= 1'b1;
            end else begin
                bit_index <= bit_index - 3'd1;
            end
        end else begin
            if (final_sample_seen) begin
                busy <= 1'b0;
                cs_n <= 1'b1;
                sclk <= 1'b0;
                done <= 1'b1;
                rx_data <= rx_shift;
                final_sample_seen <= 1'b0;
            end else begin
                sclk <= 1'b0;
                mosi <= tx_latched[bit_index];
            end
        end
    end
endmodule
